View.java revision eaa0a04f83113e2cafb8c2044ae2107d15dd8036
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.Insets;
28import android.graphics.Interpolator;
29import android.graphics.LinearGradient;
30import android.graphics.Matrix;
31import android.graphics.Paint;
32import android.graphics.PixelFormat;
33import android.graphics.Point;
34import android.graphics.PorterDuff;
35import android.graphics.PorterDuffXfermode;
36import android.graphics.Rect;
37import android.graphics.RectF;
38import android.graphics.Region;
39import android.graphics.Shader;
40import android.graphics.drawable.ColorDrawable;
41import android.graphics.drawable.Drawable;
42import android.os.Handler;
43import android.os.IBinder;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.text.TextUtils;
49import android.util.AttributeSet;
50import android.util.FloatProperty;
51import android.util.LocaleUtil;
52import android.util.Log;
53import android.util.Pool;
54import android.util.Poolable;
55import android.util.PoolableManager;
56import android.util.Pools;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
64import android.view.accessibility.AccessibilityNodeInfo;
65import android.view.accessibility.AccessibilityNodeProvider;
66import android.view.animation.Animation;
67import android.view.animation.AnimationUtils;
68import android.view.animation.Transformation;
69import android.view.inputmethod.EditorInfo;
70import android.view.inputmethod.InputConnection;
71import android.view.inputmethod.InputMethodManager;
72import android.widget.ScrollBarDrawable;
73
74import static android.os.Build.VERSION_CODES.*;
75import static java.lang.Math.max;
76
77import com.android.internal.R;
78import com.android.internal.util.Predicate;
79import com.android.internal.view.menu.MenuBuilder;
80
81import java.lang.ref.WeakReference;
82import java.lang.reflect.InvocationTargetException;
83import java.lang.reflect.Method;
84import java.util.ArrayList;
85import java.util.Arrays;
86import java.util.Locale;
87import java.util.concurrent.CopyOnWriteArrayList;
88
89/**
90 * <p>
91 * This class represents the basic building block for user interface components. A View
92 * occupies a rectangular area on the screen and is responsible for drawing and
93 * event handling. View is the base class for <em>widgets</em>, which are
94 * used to create interactive UI components (buttons, text fields, etc.). The
95 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
96 * are invisible containers that hold other Views (or other ViewGroups) and define
97 * their layout properties.
98 * </p>
99 *
100 * <div class="special reference">
101 * <h3>Developer Guides</h3>
102 * <p>For information about using this class to develop your application's user interface,
103 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
104 * </div>
105 *
106 * <a name="Using"></a>
107 * <h3>Using Views</h3>
108 * <p>
109 * All of the views in a window are arranged in a single tree. You can add views
110 * either from code or by specifying a tree of views in one or more XML layout
111 * files. There are many specialized subclasses of views that act as controls or
112 * are capable of displaying text, images, or other content.
113 * </p>
114 * <p>
115 * Once you have created a tree of views, there are typically a few types of
116 * common operations you may wish to perform:
117 * <ul>
118 * <li><strong>Set properties:</strong> for example setting the text of a
119 * {@link android.widget.TextView}. The available properties and the methods
120 * that set them will vary among the different subclasses of views. Note that
121 * properties that are known at build time can be set in the XML layout
122 * files.</li>
123 * <li><strong>Set focus:</strong> The framework will handled moving focus in
124 * response to user input. To force focus to a specific view, call
125 * {@link #requestFocus}.</li>
126 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
127 * that will be notified when something interesting happens to the view. For
128 * example, all views will let you set a listener to be notified when the view
129 * gains or loses focus. You can register such a listener using
130 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
131 * Other view subclasses offer more specialized listeners. For example, a Button
132 * exposes a listener to notify clients when the button is clicked.</li>
133 * <li><strong>Set visibility:</strong> You can hide or show views using
134 * {@link #setVisibility(int)}.</li>
135 * </ul>
136 * </p>
137 * <p><em>
138 * Note: The Android framework is responsible for measuring, laying out and
139 * drawing views. You should not call methods that perform these actions on
140 * views yourself unless you are actually implementing a
141 * {@link android.view.ViewGroup}.
142 * </em></p>
143 *
144 * <a name="Lifecycle"></a>
145 * <h3>Implementing a Custom View</h3>
146 *
147 * <p>
148 * To implement a custom view, you will usually begin by providing overrides for
149 * some of the standard methods that the framework calls on all views. You do
150 * not need to override all of these methods. In fact, you can start by just
151 * overriding {@link #onDraw(android.graphics.Canvas)}.
152 * <table border="2" width="85%" align="center" cellpadding="5">
153 *     <thead>
154 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
155 *     </thead>
156 *
157 *     <tbody>
158 *     <tr>
159 *         <td rowspan="2">Creation</td>
160 *         <td>Constructors</td>
161 *         <td>There is a form of the constructor that are called when the view
162 *         is created from code and a form that is called when the view is
163 *         inflated from a layout file. The second form should parse and apply
164 *         any attributes defined in the layout file.
165 *         </td>
166 *     </tr>
167 *     <tr>
168 *         <td><code>{@link #onFinishInflate()}</code></td>
169 *         <td>Called after a view and all of its children has been inflated
170 *         from XML.</td>
171 *     </tr>
172 *
173 *     <tr>
174 *         <td rowspan="3">Layout</td>
175 *         <td><code>{@link #onMeasure(int, int)}</code></td>
176 *         <td>Called to determine the size requirements for this view and all
177 *         of its children.
178 *         </td>
179 *     </tr>
180 *     <tr>
181 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
182 *         <td>Called when this view should assign a size and position to all
183 *         of its children.
184 *         </td>
185 *     </tr>
186 *     <tr>
187 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
188 *         <td>Called when the size of this view has changed.
189 *         </td>
190 *     </tr>
191 *
192 *     <tr>
193 *         <td>Drawing</td>
194 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
195 *         <td>Called when the view should render its content.
196 *         </td>
197 *     </tr>
198 *
199 *     <tr>
200 *         <td rowspan="4">Event processing</td>
201 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
202 *         <td>Called when a new key event occurs.
203 *         </td>
204 *     </tr>
205 *     <tr>
206 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
207 *         <td>Called when a key up event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
212 *         <td>Called when a trackball motion event occurs.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
217 *         <td>Called when a touch screen motion event occurs.
218 *         </td>
219 *     </tr>
220 *
221 *     <tr>
222 *         <td rowspan="2">Focus</td>
223 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
224 *         <td>Called when the view gains or loses focus.
225 *         </td>
226 *     </tr>
227 *
228 *     <tr>
229 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
230 *         <td>Called when the window containing the view gains or loses focus.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td rowspan="3">Attaching</td>
236 *         <td><code>{@link #onAttachedToWindow()}</code></td>
237 *         <td>Called when the view is attached to a window.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td><code>{@link #onDetachedFromWindow}</code></td>
243 *         <td>Called when the view is detached from its window.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
249 *         <td>Called when the visibility of the window containing the view
250 *         has changed.
251 *         </td>
252 *     </tr>
253 *     </tbody>
254 *
255 * </table>
256 * </p>
257 *
258 * <a name="IDs"></a>
259 * <h3>IDs</h3>
260 * Views may have an integer id associated with them. These ids are typically
261 * assigned in the layout XML files, and are used to find specific views within
262 * the view tree. A common pattern is to:
263 * <ul>
264 * <li>Define a Button in the layout file and assign it a unique ID.
265 * <pre>
266 * &lt;Button
267 *     android:id="@+id/my_button"
268 *     android:layout_width="wrap_content"
269 *     android:layout_height="wrap_content"
270 *     android:text="@string/my_button_text"/&gt;
271 * </pre></li>
272 * <li>From the onCreate method of an Activity, find the Button
273 * <pre class="prettyprint">
274 *      Button myButton = (Button) findViewById(R.id.my_button);
275 * </pre></li>
276 * </ul>
277 * <p>
278 * View IDs need not be unique throughout the tree, but it is good practice to
279 * ensure that they are at least unique within the part of the tree you are
280 * searching.
281 * </p>
282 *
283 * <a name="Position"></a>
284 * <h3>Position</h3>
285 * <p>
286 * The geometry of a view is that of a rectangle. A view has a location,
287 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
288 * two dimensions, expressed as a width and a height. The unit for location
289 * and dimensions is the pixel.
290 * </p>
291 *
292 * <p>
293 * It is possible to retrieve the location of a view by invoking the methods
294 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
295 * coordinate of the rectangle representing the view. The latter returns the
296 * top, or Y, coordinate of the rectangle representing the view. These methods
297 * both return the location of the view relative to its parent. For instance,
298 * when getLeft() returns 20, that means the view is located 20 pixels to the
299 * right of the left edge of its direct parent.
300 * </p>
301 *
302 * <p>
303 * In addition, several convenience methods are offered to avoid unnecessary
304 * computations, namely {@link #getRight()} and {@link #getBottom()}.
305 * These methods return the coordinates of the right and bottom edges of the
306 * rectangle representing the view. For instance, calling {@link #getRight()}
307 * is similar to the following computation: <code>getLeft() + getWidth()</code>
308 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
309 * </p>
310 *
311 * <a name="SizePaddingMargins"></a>
312 * <h3>Size, padding and margins</h3>
313 * <p>
314 * The size of a view is expressed with a width and a height. A view actually
315 * possess two pairs of width and height values.
316 * </p>
317 *
318 * <p>
319 * The first pair is known as <em>measured width</em> and
320 * <em>measured height</em>. These dimensions define how big a view wants to be
321 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
322 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
323 * and {@link #getMeasuredHeight()}.
324 * </p>
325 *
326 * <p>
327 * The second pair is simply known as <em>width</em> and <em>height</em>, or
328 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
329 * dimensions define the actual size of the view on screen, at drawing time and
330 * after layout. These values may, but do not have to, be different from the
331 * measured width and height. The width and height can be obtained by calling
332 * {@link #getWidth()} and {@link #getHeight()}.
333 * </p>
334 *
335 * <p>
336 * To measure its dimensions, a view takes into account its padding. The padding
337 * is expressed in pixels for the left, top, right and bottom parts of the view.
338 * Padding can be used to offset the content of the view by a specific amount of
339 * pixels. For instance, a left padding of 2 will push the view's content by
340 * 2 pixels to the right of the left edge. Padding can be set using the
341 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
342 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
343 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
344 * {@link #getPaddingEnd()}.
345 * </p>
346 *
347 * <p>
348 * Even though a view can define a padding, it does not provide any support for
349 * margins. However, view groups provide such a support. Refer to
350 * {@link android.view.ViewGroup} and
351 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
352 * </p>
353 *
354 * <a name="Layout"></a>
355 * <h3>Layout</h3>
356 * <p>
357 * Layout is a two pass process: a measure pass and a layout pass. The measuring
358 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
359 * of the view tree. Each view pushes dimension specifications down the tree
360 * during the recursion. At the end of the measure pass, every view has stored
361 * its measurements. The second pass happens in
362 * {@link #layout(int,int,int,int)} and is also top-down. During
363 * this pass each parent is responsible for positioning all of its children
364 * using the sizes computed in the measure pass.
365 * </p>
366 *
367 * <p>
368 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
369 * {@link #getMeasuredHeight()} values must be set, along with those for all of
370 * that view's descendants. A view's measured width and measured height values
371 * must respect the constraints imposed by the view's parents. This guarantees
372 * that at the end of the measure pass, all parents accept all of their
373 * children's measurements. A parent view may call measure() more than once on
374 * its children. For example, the parent may measure each child once with
375 * unspecified dimensions to find out how big they want to be, then call
376 * measure() on them again with actual numbers if the sum of all the children's
377 * unconstrained sizes is too big or too small.
378 * </p>
379 *
380 * <p>
381 * The measure pass uses two classes to communicate dimensions. The
382 * {@link MeasureSpec} class is used by views to tell their parents how they
383 * want to be measured and positioned. The base LayoutParams class just
384 * describes how big the view wants to be for both width and height. For each
385 * dimension, it can specify one of:
386 * <ul>
387 * <li> an exact number
388 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
389 * (minus padding)
390 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
391 * enclose its content (plus padding).
392 * </ul>
393 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
394 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
395 * an X and Y value.
396 * </p>
397 *
398 * <p>
399 * MeasureSpecs are used to push requirements down the tree from parent to
400 * child. A MeasureSpec can be in one of three modes:
401 * <ul>
402 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
403 * of a child view. For example, a LinearLayout may call measure() on its child
404 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
405 * tall the child view wants to be given a width of 240 pixels.
406 * <li>EXACTLY: This is used by the parent to impose an exact size on the
407 * child. The child must use this size, and guarantee that all of its
408 * descendants will fit within this size.
409 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
410 * child. The child must gurantee that it and all of its descendants will fit
411 * within this size.
412 * </ul>
413 * </p>
414 *
415 * <p>
416 * To intiate a layout, call {@link #requestLayout}. This method is typically
417 * called by a view on itself when it believes that is can no longer fit within
418 * its current bounds.
419 * </p>
420 *
421 * <a name="Drawing"></a>
422 * <h3>Drawing</h3>
423 * <p>
424 * Drawing is handled by walking the tree and rendering each view that
425 * intersects the invalid region. Because the tree is traversed in-order,
426 * this means that parents will draw before (i.e., behind) their children, with
427 * siblings drawn in the order they appear in the tree.
428 * If you set a background drawable for a View, then the View will draw it for you
429 * before calling back to its <code>onDraw()</code> method.
430 * </p>
431 *
432 * <p>
433 * Note that the framework will not draw views that are not in the invalid region.
434 * </p>
435 *
436 * <p>
437 * To force a view to draw, call {@link #invalidate()}.
438 * </p>
439 *
440 * <a name="EventHandlingThreading"></a>
441 * <h3>Event Handling and Threading</h3>
442 * <p>
443 * The basic cycle of a view is as follows:
444 * <ol>
445 * <li>An event comes in and is dispatched to the appropriate view. The view
446 * handles the event and notifies any listeners.</li>
447 * <li>If in the course of processing the event, the view's bounds may need
448 * to be changed, the view will call {@link #requestLayout()}.</li>
449 * <li>Similarly, if in the course of processing the event the view's appearance
450 * may need to be changed, the view will call {@link #invalidate()}.</li>
451 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
452 * the framework will take care of measuring, laying out, and drawing the tree
453 * as appropriate.</li>
454 * </ol>
455 * </p>
456 *
457 * <p><em>Note: The entire view tree is single threaded. You must always be on
458 * the UI thread when calling any method on any view.</em>
459 * If you are doing work on other threads and want to update the state of a view
460 * from that thread, you should use a {@link Handler}.
461 * </p>
462 *
463 * <a name="FocusHandling"></a>
464 * <h3>Focus Handling</h3>
465 * <p>
466 * The framework will handle routine focus movement in response to user input.
467 * This includes changing the focus as views are removed or hidden, or as new
468 * views become available. Views indicate their willingness to take focus
469 * through the {@link #isFocusable} method. To change whether a view can take
470 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
471 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
472 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
473 * </p>
474 * <p>
475 * Focus movement is based on an algorithm which finds the nearest neighbor in a
476 * given direction. In rare cases, the default algorithm may not match the
477 * intended behavior of the developer. In these situations, you can provide
478 * explicit overrides by using these XML attributes in the layout file:
479 * <pre>
480 * nextFocusDown
481 * nextFocusLeft
482 * nextFocusRight
483 * nextFocusUp
484 * </pre>
485 * </p>
486 *
487 *
488 * <p>
489 * To get a particular view to take focus, call {@link #requestFocus()}.
490 * </p>
491 *
492 * <a name="TouchMode"></a>
493 * <h3>Touch Mode</h3>
494 * <p>
495 * When a user is navigating a user interface via directional keys such as a D-pad, it is
496 * necessary to give focus to actionable items such as buttons so the user can see
497 * what will take input.  If the device has touch capabilities, however, and the user
498 * begins interacting with the interface by touching it, it is no longer necessary to
499 * always highlight, or give focus to, a particular view.  This motivates a mode
500 * for interaction named 'touch mode'.
501 * </p>
502 * <p>
503 * For a touch capable device, once the user touches the screen, the device
504 * will enter touch mode.  From this point onward, only views for which
505 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
506 * Other views that are touchable, like buttons, will not take focus when touched; they will
507 * only fire the on click listeners.
508 * </p>
509 * <p>
510 * Any time a user hits a directional key, such as a D-pad direction, the view device will
511 * exit touch mode, and find a view to take focus, so that the user may resume interacting
512 * with the user interface without touching the screen again.
513 * </p>
514 * <p>
515 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
516 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
517 * </p>
518 *
519 * <a name="Scrolling"></a>
520 * <h3>Scrolling</h3>
521 * <p>
522 * The framework provides basic support for views that wish to internally
523 * scroll their content. This includes keeping track of the X and Y scroll
524 * offset as well as mechanisms for drawing scrollbars. See
525 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
526 * {@link #awakenScrollBars()} for more details.
527 * </p>
528 *
529 * <a name="Tags"></a>
530 * <h3>Tags</h3>
531 * <p>
532 * Unlike IDs, tags are not used to identify views. Tags are essentially an
533 * extra piece of information that can be associated with a view. They are most
534 * often used as a convenience to store data related to views in the views
535 * themselves rather than by putting them in a separate structure.
536 * </p>
537 *
538 * <a name="Animation"></a>
539 * <h3>Animation</h3>
540 * <p>
541 * You can attach an {@link Animation} object to a view using
542 * {@link #setAnimation(Animation)} or
543 * {@link #startAnimation(Animation)}. The animation can alter the scale,
544 * rotation, translation and alpha of a view over time. If the animation is
545 * attached to a view that has children, the animation will affect the entire
546 * subtree rooted by that node. When an animation is started, the framework will
547 * take care of redrawing the appropriate views until the animation completes.
548 * </p>
549 * <p>
550 * Starting with Android 3.0, the preferred way of animating views is to use the
551 * {@link android.animation} package APIs.
552 * </p>
553 *
554 * <a name="Security"></a>
555 * <h3>Security</h3>
556 * <p>
557 * Sometimes it is essential that an application be able to verify that an action
558 * is being performed with the full knowledge and consent of the user, such as
559 * granting a permission request, making a purchase or clicking on an advertisement.
560 * Unfortunately, a malicious application could try to spoof the user into
561 * performing these actions, unaware, by concealing the intended purpose of the view.
562 * As a remedy, the framework offers a touch filtering mechanism that can be used to
563 * improve the security of views that provide access to sensitive functionality.
564 * </p><p>
565 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
566 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
567 * will discard touches that are received whenever the view's window is obscured by
568 * another visible window.  As a result, the view will not receive touches whenever a
569 * toast, dialog or other window appears above the view's window.
570 * </p><p>
571 * For more fine-grained control over security, consider overriding the
572 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
573 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
574 * </p>
575 *
576 * @attr ref android.R.styleable#View_alpha
577 * @attr ref android.R.styleable#View_background
578 * @attr ref android.R.styleable#View_clickable
579 * @attr ref android.R.styleable#View_contentDescription
580 * @attr ref android.R.styleable#View_drawingCacheQuality
581 * @attr ref android.R.styleable#View_duplicateParentState
582 * @attr ref android.R.styleable#View_id
583 * @attr ref android.R.styleable#View_requiresFadingEdge
584 * @attr ref android.R.styleable#View_fadeScrollbars
585 * @attr ref android.R.styleable#View_fadingEdgeLength
586 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
587 * @attr ref android.R.styleable#View_fitsSystemWindows
588 * @attr ref android.R.styleable#View_isScrollContainer
589 * @attr ref android.R.styleable#View_focusable
590 * @attr ref android.R.styleable#View_focusableInTouchMode
591 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
592 * @attr ref android.R.styleable#View_keepScreenOn
593 * @attr ref android.R.styleable#View_layerType
594 * @attr ref android.R.styleable#View_longClickable
595 * @attr ref android.R.styleable#View_minHeight
596 * @attr ref android.R.styleable#View_minWidth
597 * @attr ref android.R.styleable#View_nextFocusDown
598 * @attr ref android.R.styleable#View_nextFocusLeft
599 * @attr ref android.R.styleable#View_nextFocusRight
600 * @attr ref android.R.styleable#View_nextFocusUp
601 * @attr ref android.R.styleable#View_onClick
602 * @attr ref android.R.styleable#View_padding
603 * @attr ref android.R.styleable#View_paddingBottom
604 * @attr ref android.R.styleable#View_paddingLeft
605 * @attr ref android.R.styleable#View_paddingRight
606 * @attr ref android.R.styleable#View_paddingTop
607 * @attr ref android.R.styleable#View_paddingStart
608 * @attr ref android.R.styleable#View_paddingEnd
609 * @attr ref android.R.styleable#View_saveEnabled
610 * @attr ref android.R.styleable#View_rotation
611 * @attr ref android.R.styleable#View_rotationX
612 * @attr ref android.R.styleable#View_rotationY
613 * @attr ref android.R.styleable#View_scaleX
614 * @attr ref android.R.styleable#View_scaleY
615 * @attr ref android.R.styleable#View_scrollX
616 * @attr ref android.R.styleable#View_scrollY
617 * @attr ref android.R.styleable#View_scrollbarSize
618 * @attr ref android.R.styleable#View_scrollbarStyle
619 * @attr ref android.R.styleable#View_scrollbars
620 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
621 * @attr ref android.R.styleable#View_scrollbarFadeDuration
622 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
623 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
624 * @attr ref android.R.styleable#View_scrollbarThumbVertical
625 * @attr ref android.R.styleable#View_scrollbarTrackVertical
626 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
627 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
628 * @attr ref android.R.styleable#View_soundEffectsEnabled
629 * @attr ref android.R.styleable#View_tag
630 * @attr ref android.R.styleable#View_textAlignment
631 * @attr ref android.R.styleable#View_transformPivotX
632 * @attr ref android.R.styleable#View_transformPivotY
633 * @attr ref android.R.styleable#View_translationX
634 * @attr ref android.R.styleable#View_translationY
635 * @attr ref android.R.styleable#View_visibility
636 *
637 * @see android.view.ViewGroup
638 */
639public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
640        AccessibilityEventSource {
641    private static final boolean DBG = false;
642
643    /**
644     * The logging tag used by this class with android.util.Log.
645     */
646    protected static final String VIEW_LOG_TAG = "View";
647
648    /**
649     * Used to mark a View that has no ID.
650     */
651    public static final int NO_ID = -1;
652
653    /**
654     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
655     * calling setFlags.
656     */
657    private static final int NOT_FOCUSABLE = 0x00000000;
658
659    /**
660     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
661     * setFlags.
662     */
663    private static final int FOCUSABLE = 0x00000001;
664
665    /**
666     * Mask for use with setFlags indicating bits used for focus.
667     */
668    private static final int FOCUSABLE_MASK = 0x00000001;
669
670    /**
671     * This view will adjust its padding to fit sytem windows (e.g. status bar)
672     */
673    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
674
675    /**
676     * This view is visible.
677     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
678     * android:visibility}.
679     */
680    public static final int VISIBLE = 0x00000000;
681
682    /**
683     * This view is invisible, but it still takes up space for layout purposes.
684     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
685     * android:visibility}.
686     */
687    public static final int INVISIBLE = 0x00000004;
688
689    /**
690     * This view is invisible, and it doesn't take any space for layout
691     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
692     * android:visibility}.
693     */
694    public static final int GONE = 0x00000008;
695
696    /**
697     * Mask for use with setFlags indicating bits used for visibility.
698     * {@hide}
699     */
700    static final int VISIBILITY_MASK = 0x0000000C;
701
702    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
703
704    /**
705     * This view is enabled. Interpretation varies by subclass.
706     * Use with ENABLED_MASK when calling setFlags.
707     * {@hide}
708     */
709    static final int ENABLED = 0x00000000;
710
711    /**
712     * This view is disabled. Interpretation varies by subclass.
713     * Use with ENABLED_MASK when calling setFlags.
714     * {@hide}
715     */
716    static final int DISABLED = 0x00000020;
717
718   /**
719    * Mask for use with setFlags indicating bits used for indicating whether
720    * this view is enabled
721    * {@hide}
722    */
723    static final int ENABLED_MASK = 0x00000020;
724
725    /**
726     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
727     * called and further optimizations will be performed. It is okay to have
728     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
729     * {@hide}
730     */
731    static final int WILL_NOT_DRAW = 0x00000080;
732
733    /**
734     * Mask for use with setFlags indicating bits used for indicating whether
735     * this view is will draw
736     * {@hide}
737     */
738    static final int DRAW_MASK = 0x00000080;
739
740    /**
741     * <p>This view doesn't show scrollbars.</p>
742     * {@hide}
743     */
744    static final int SCROLLBARS_NONE = 0x00000000;
745
746    /**
747     * <p>This view shows horizontal scrollbars.</p>
748     * {@hide}
749     */
750    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
751
752    /**
753     * <p>This view shows vertical scrollbars.</p>
754     * {@hide}
755     */
756    static final int SCROLLBARS_VERTICAL = 0x00000200;
757
758    /**
759     * <p>Mask for use with setFlags indicating bits used for indicating which
760     * scrollbars are enabled.</p>
761     * {@hide}
762     */
763    static final int SCROLLBARS_MASK = 0x00000300;
764
765    /**
766     * Indicates that the view should filter touches when its window is obscured.
767     * Refer to the class comments for more information about this security feature.
768     * {@hide}
769     */
770    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
771
772    /**
773     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
774     * that they are optional and should be skipped if the window has
775     * requested system UI flags that ignore those insets for layout.
776     */
777    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
778
779    /**
780     * <p>This view doesn't show fading edges.</p>
781     * {@hide}
782     */
783    static final int FADING_EDGE_NONE = 0x00000000;
784
785    /**
786     * <p>This view shows horizontal fading edges.</p>
787     * {@hide}
788     */
789    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
790
791    /**
792     * <p>This view shows vertical fading edges.</p>
793     * {@hide}
794     */
795    static final int FADING_EDGE_VERTICAL = 0x00002000;
796
797    /**
798     * <p>Mask for use with setFlags indicating bits used for indicating which
799     * fading edges are enabled.</p>
800     * {@hide}
801     */
802    static final int FADING_EDGE_MASK = 0x00003000;
803
804    /**
805     * <p>Indicates this view can be clicked. When clickable, a View reacts
806     * to clicks by notifying the OnClickListener.<p>
807     * {@hide}
808     */
809    static final int CLICKABLE = 0x00004000;
810
811    /**
812     * <p>Indicates this view is caching its drawing into a bitmap.</p>
813     * {@hide}
814     */
815    static final int DRAWING_CACHE_ENABLED = 0x00008000;
816
817    /**
818     * <p>Indicates that no icicle should be saved for this view.<p>
819     * {@hide}
820     */
821    static final int SAVE_DISABLED = 0x000010000;
822
823    /**
824     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
825     * property.</p>
826     * {@hide}
827     */
828    static final int SAVE_DISABLED_MASK = 0x000010000;
829
830    /**
831     * <p>Indicates that no drawing cache should ever be created for this view.<p>
832     * {@hide}
833     */
834    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
835
836    /**
837     * <p>Indicates this view can take / keep focus when int touch mode.</p>
838     * {@hide}
839     */
840    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
841
842    /**
843     * <p>Enables low quality mode for the drawing cache.</p>
844     */
845    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
846
847    /**
848     * <p>Enables high quality mode for the drawing cache.</p>
849     */
850    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
851
852    /**
853     * <p>Enables automatic quality mode for the drawing cache.</p>
854     */
855    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
856
857    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
858            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
859    };
860
861    /**
862     * <p>Mask for use with setFlags indicating bits used for the cache
863     * quality property.</p>
864     * {@hide}
865     */
866    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
867
868    /**
869     * <p>
870     * Indicates this view can be long clicked. When long clickable, a View
871     * reacts to long clicks by notifying the OnLongClickListener or showing a
872     * context menu.
873     * </p>
874     * {@hide}
875     */
876    static final int LONG_CLICKABLE = 0x00200000;
877
878    /**
879     * <p>Indicates that this view gets its drawable states from its direct parent
880     * and ignores its original internal states.</p>
881     *
882     * @hide
883     */
884    static final int DUPLICATE_PARENT_STATE = 0x00400000;
885
886    /**
887     * The scrollbar style to display the scrollbars inside the content area,
888     * without increasing the padding. The scrollbars will be overlaid with
889     * translucency on the view's content.
890     */
891    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
892
893    /**
894     * The scrollbar style to display the scrollbars inside the padded area,
895     * increasing the padding of the view. The scrollbars will not overlap the
896     * content area of the view.
897     */
898    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
899
900    /**
901     * The scrollbar style to display the scrollbars at the edge of the view,
902     * without increasing the padding. The scrollbars will be overlaid with
903     * translucency.
904     */
905    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
906
907    /**
908     * The scrollbar style to display the scrollbars at the edge of the view,
909     * increasing the padding of the view. The scrollbars will only overlap the
910     * background, if any.
911     */
912    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
913
914    /**
915     * Mask to check if the scrollbar style is overlay or inset.
916     * {@hide}
917     */
918    static final int SCROLLBARS_INSET_MASK = 0x01000000;
919
920    /**
921     * Mask to check if the scrollbar style is inside or outside.
922     * {@hide}
923     */
924    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
925
926    /**
927     * Mask for scrollbar style.
928     * {@hide}
929     */
930    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
931
932    /**
933     * View flag indicating that the screen should remain on while the
934     * window containing this view is visible to the user.  This effectively
935     * takes care of automatically setting the WindowManager's
936     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
937     */
938    public static final int KEEP_SCREEN_ON = 0x04000000;
939
940    /**
941     * View flag indicating whether this view should have sound effects enabled
942     * for events such as clicking and touching.
943     */
944    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
945
946    /**
947     * View flag indicating whether this view should have haptic feedback
948     * enabled for events such as long presses.
949     */
950    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
951
952    /**
953     * <p>Indicates that the view hierarchy should stop saving state when
954     * it reaches this view.  If state saving is initiated immediately at
955     * the view, it will be allowed.
956     * {@hide}
957     */
958    static final int PARENT_SAVE_DISABLED = 0x20000000;
959
960    /**
961     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
962     * {@hide}
963     */
964    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
965
966    /**
967     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
968     * should add all focusable Views regardless if they are focusable in touch mode.
969     */
970    public static final int FOCUSABLES_ALL = 0x00000000;
971
972    /**
973     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
974     * should add only Views focusable in touch mode.
975     */
976    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
977
978    /**
979     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
980     * should add only accessibility focusable Views.
981     *
982     * @hide
983     */
984    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
985
986    /**
987     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
988     * item.
989     */
990    public static final int FOCUS_BACKWARD = 0x00000001;
991
992    /**
993     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
994     * item.
995     */
996    public static final int FOCUS_FORWARD = 0x00000002;
997
998    /**
999     * Use with {@link #focusSearch(int)}. Move focus to the left.
1000     */
1001    public static final int FOCUS_LEFT = 0x00000011;
1002
1003    /**
1004     * Use with {@link #focusSearch(int)}. Move focus up.
1005     */
1006    public static final int FOCUS_UP = 0x00000021;
1007
1008    /**
1009     * Use with {@link #focusSearch(int)}. Move focus to the right.
1010     */
1011    public static final int FOCUS_RIGHT = 0x00000042;
1012
1013    /**
1014     * Use with {@link #focusSearch(int)}. Move focus down.
1015     */
1016    public static final int FOCUS_DOWN = 0x00000082;
1017
1018    // Accessibility focus directions.
1019
1020    /**
1021     * The accessibility focus which is the current user position when
1022     * interacting with the accessibility framework.
1023     */
1024    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1025
1026    /**
1027     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1028     */
1029    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1030
1031    /**
1032     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1033     */
1034    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1035
1036    /**
1037     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1038     */
1039    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1040
1041    /**
1042     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1043     */
1044    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1045
1046    /**
1047     * Use with {@link #focusSearch(int)}. Move acessibility focus to the next view.
1048     */
1049    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1050
1051    /**
1052     * Use with {@link #focusSearch(int)}. Move acessibility focus to the previous view.
1053     */
1054    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1055
1056    /**
1057     * Use with {@link #focusSearch(int)}. Move acessibility focus in a view.
1058     */
1059    public static final int ACCESSIBILITY_FOCUS_IN = 0x00000004 | FOCUS_ACCESSIBILITY;
1060
1061    /**
1062     * Use with {@link #focusSearch(int)}. Move acessibility focus out of a view.
1063     */
1064    public static final int ACCESSIBILITY_FOCUS_OUT = 0x00000008 | FOCUS_ACCESSIBILITY;
1065
1066    /**
1067     * Bits of {@link #getMeasuredWidthAndState()} and
1068     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1069     */
1070    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1071
1072    /**
1073     * Bits of {@link #getMeasuredWidthAndState()} and
1074     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1075     */
1076    public static final int MEASURED_STATE_MASK = 0xff000000;
1077
1078    /**
1079     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1080     * for functions that combine both width and height into a single int,
1081     * such as {@link #getMeasuredState()} and the childState argument of
1082     * {@link #resolveSizeAndState(int, int, int)}.
1083     */
1084    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1085
1086    /**
1087     * Bit of {@link #getMeasuredWidthAndState()} and
1088     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1089     * is smaller that the space the view would like to have.
1090     */
1091    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1092
1093    /**
1094     * Base View state sets
1095     */
1096    // Singles
1097    /**
1098     * Indicates the view has no states set. States are used with
1099     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1100     * view depending on its state.
1101     *
1102     * @see android.graphics.drawable.Drawable
1103     * @see #getDrawableState()
1104     */
1105    protected static final int[] EMPTY_STATE_SET;
1106    /**
1107     * Indicates the view is enabled. States are used with
1108     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1109     * view depending on its state.
1110     *
1111     * @see android.graphics.drawable.Drawable
1112     * @see #getDrawableState()
1113     */
1114    protected static final int[] ENABLED_STATE_SET;
1115    /**
1116     * Indicates the view is focused. States are used with
1117     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1118     * view depending on its state.
1119     *
1120     * @see android.graphics.drawable.Drawable
1121     * @see #getDrawableState()
1122     */
1123    protected static final int[] FOCUSED_STATE_SET;
1124    /**
1125     * Indicates the view is selected. States are used with
1126     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1127     * view depending on its state.
1128     *
1129     * @see android.graphics.drawable.Drawable
1130     * @see #getDrawableState()
1131     */
1132    protected static final int[] SELECTED_STATE_SET;
1133    /**
1134     * Indicates the view is pressed. States are used with
1135     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1136     * view depending on its state.
1137     *
1138     * @see android.graphics.drawable.Drawable
1139     * @see #getDrawableState()
1140     * @hide
1141     */
1142    protected static final int[] PRESSED_STATE_SET;
1143    /**
1144     * Indicates the view's window has focus. States are used with
1145     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1146     * view depending on its state.
1147     *
1148     * @see android.graphics.drawable.Drawable
1149     * @see #getDrawableState()
1150     */
1151    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1152    // Doubles
1153    /**
1154     * Indicates the view is enabled and has the focus.
1155     *
1156     * @see #ENABLED_STATE_SET
1157     * @see #FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is enabled and selected.
1162     *
1163     * @see #ENABLED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     */
1166    protected static final int[] ENABLED_SELECTED_STATE_SET;
1167    /**
1168     * Indicates the view is enabled and that its window has focus.
1169     *
1170     * @see #ENABLED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is focused and selected.
1176     *
1177     * @see #FOCUSED_STATE_SET
1178     * @see #SELECTED_STATE_SET
1179     */
1180    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1181    /**
1182     * Indicates the view has the focus and that its window has the focus.
1183     *
1184     * @see #FOCUSED_STATE_SET
1185     * @see #WINDOW_FOCUSED_STATE_SET
1186     */
1187    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1188    /**
1189     * Indicates the view is selected and that its window has the focus.
1190     *
1191     * @see #SELECTED_STATE_SET
1192     * @see #WINDOW_FOCUSED_STATE_SET
1193     */
1194    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1195    // Triples
1196    /**
1197     * Indicates the view is enabled, focused and selected.
1198     *
1199     * @see #ENABLED_STATE_SET
1200     * @see #FOCUSED_STATE_SET
1201     * @see #SELECTED_STATE_SET
1202     */
1203    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1204    /**
1205     * Indicates the view is enabled, focused and its window has the focus.
1206     *
1207     * @see #ENABLED_STATE_SET
1208     * @see #FOCUSED_STATE_SET
1209     * @see #WINDOW_FOCUSED_STATE_SET
1210     */
1211    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1212    /**
1213     * Indicates the view is enabled, selected and its window has the focus.
1214     *
1215     * @see #ENABLED_STATE_SET
1216     * @see #SELECTED_STATE_SET
1217     * @see #WINDOW_FOCUSED_STATE_SET
1218     */
1219    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1220    /**
1221     * Indicates the view is focused, selected and its window has the focus.
1222     *
1223     * @see #FOCUSED_STATE_SET
1224     * @see #SELECTED_STATE_SET
1225     * @see #WINDOW_FOCUSED_STATE_SET
1226     */
1227    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1228    /**
1229     * Indicates the view is enabled, focused, selected and its window
1230     * has the focus.
1231     *
1232     * @see #ENABLED_STATE_SET
1233     * @see #FOCUSED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     * @see #WINDOW_FOCUSED_STATE_SET
1236     */
1237    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed and its window has the focus.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is pressed and selected.
1247     *
1248     * @see #PRESSED_STATE_SET
1249     * @see #SELECTED_STATE_SET
1250     */
1251    protected static final int[] PRESSED_SELECTED_STATE_SET;
1252    /**
1253     * Indicates the view is pressed, selected and its window has the focus.
1254     *
1255     * @see #PRESSED_STATE_SET
1256     * @see #SELECTED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is pressed and focused.
1262     *
1263     * @see #PRESSED_STATE_SET
1264     * @see #FOCUSED_STATE_SET
1265     */
1266    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1267    /**
1268     * Indicates the view is pressed, focused and its window has the focus.
1269     *
1270     * @see #PRESSED_STATE_SET
1271     * @see #FOCUSED_STATE_SET
1272     * @see #WINDOW_FOCUSED_STATE_SET
1273     */
1274    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1275    /**
1276     * Indicates the view is pressed, focused and selected.
1277     *
1278     * @see #PRESSED_STATE_SET
1279     * @see #SELECTED_STATE_SET
1280     * @see #FOCUSED_STATE_SET
1281     */
1282    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1283    /**
1284     * Indicates the view is pressed, focused, selected and its window has the focus.
1285     *
1286     * @see #PRESSED_STATE_SET
1287     * @see #FOCUSED_STATE_SET
1288     * @see #SELECTED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed and enabled.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #ENABLED_STATE_SET
1297     */
1298    protected static final int[] PRESSED_ENABLED_STATE_SET;
1299    /**
1300     * Indicates the view is pressed, enabled and its window has the focus.
1301     *
1302     * @see #PRESSED_STATE_SET
1303     * @see #ENABLED_STATE_SET
1304     * @see #WINDOW_FOCUSED_STATE_SET
1305     */
1306    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1307    /**
1308     * Indicates the view is pressed, enabled and selected.
1309     *
1310     * @see #PRESSED_STATE_SET
1311     * @see #ENABLED_STATE_SET
1312     * @see #SELECTED_STATE_SET
1313     */
1314    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1315    /**
1316     * Indicates the view is pressed, enabled, selected and its window has the
1317     * focus.
1318     *
1319     * @see #PRESSED_STATE_SET
1320     * @see #ENABLED_STATE_SET
1321     * @see #SELECTED_STATE_SET
1322     * @see #WINDOW_FOCUSED_STATE_SET
1323     */
1324    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1325    /**
1326     * Indicates the view is pressed, enabled and focused.
1327     *
1328     * @see #PRESSED_STATE_SET
1329     * @see #ENABLED_STATE_SET
1330     * @see #FOCUSED_STATE_SET
1331     */
1332    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1333    /**
1334     * Indicates the view is pressed, enabled, focused and its window has the
1335     * focus.
1336     *
1337     * @see #PRESSED_STATE_SET
1338     * @see #ENABLED_STATE_SET
1339     * @see #FOCUSED_STATE_SET
1340     * @see #WINDOW_FOCUSED_STATE_SET
1341     */
1342    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1343    /**
1344     * Indicates the view is pressed, enabled, focused and selected.
1345     *
1346     * @see #PRESSED_STATE_SET
1347     * @see #ENABLED_STATE_SET
1348     * @see #SELECTED_STATE_SET
1349     * @see #FOCUSED_STATE_SET
1350     */
1351    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1352    /**
1353     * Indicates the view is pressed, enabled, focused, selected and its window
1354     * has the focus.
1355     *
1356     * @see #PRESSED_STATE_SET
1357     * @see #ENABLED_STATE_SET
1358     * @see #SELECTED_STATE_SET
1359     * @see #FOCUSED_STATE_SET
1360     * @see #WINDOW_FOCUSED_STATE_SET
1361     */
1362    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1363
1364    /**
1365     * The order here is very important to {@link #getDrawableState()}
1366     */
1367    private static final int[][] VIEW_STATE_SETS;
1368
1369    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1370    static final int VIEW_STATE_SELECTED = 1 << 1;
1371    static final int VIEW_STATE_FOCUSED = 1 << 2;
1372    static final int VIEW_STATE_ENABLED = 1 << 3;
1373    static final int VIEW_STATE_PRESSED = 1 << 4;
1374    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1375    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1376    static final int VIEW_STATE_HOVERED = 1 << 7;
1377    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1378    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1379
1380    static final int[] VIEW_STATE_IDS = new int[] {
1381        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1382        R.attr.state_selected,          VIEW_STATE_SELECTED,
1383        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1384        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1385        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1386        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1387        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1388        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1389        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1390        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1391    };
1392
1393    static {
1394        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1395            throw new IllegalStateException(
1396                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1397        }
1398        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1399        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1400            int viewState = R.styleable.ViewDrawableStates[i];
1401            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1402                if (VIEW_STATE_IDS[j] == viewState) {
1403                    orderedIds[i * 2] = viewState;
1404                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1405                }
1406            }
1407        }
1408        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1409        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1410        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1411            int numBits = Integer.bitCount(i);
1412            int[] set = new int[numBits];
1413            int pos = 0;
1414            for (int j = 0; j < orderedIds.length; j += 2) {
1415                if ((i & orderedIds[j+1]) != 0) {
1416                    set[pos++] = orderedIds[j];
1417                }
1418            }
1419            VIEW_STATE_SETS[i] = set;
1420        }
1421
1422        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1423        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1424        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1425        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1427        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1428        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1430        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1431                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1432        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1433                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1434                | VIEW_STATE_FOCUSED];
1435        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1436        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1438        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1439                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1440        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1441                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1442                | VIEW_STATE_ENABLED];
1443        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1445        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1447                | VIEW_STATE_ENABLED];
1448        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1450                | VIEW_STATE_ENABLED];
1451        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1453                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1454
1455        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1456        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1457                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1458        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1459                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1460        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1462                | VIEW_STATE_PRESSED];
1463        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1465        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1470                | VIEW_STATE_PRESSED];
1471        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1473                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1476        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1477                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1478                | VIEW_STATE_PRESSED];
1479        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1481                | VIEW_STATE_PRESSED];
1482        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1483                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1484                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1485        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1486                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1487                | VIEW_STATE_PRESSED];
1488        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1489                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1490                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1491        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1492                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1493                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1494        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1495                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1496                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1497                | VIEW_STATE_PRESSED];
1498    }
1499
1500    /**
1501     * Accessibility event types that are dispatched for text population.
1502     */
1503    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1504            AccessibilityEvent.TYPE_VIEW_CLICKED
1505            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1506            | AccessibilityEvent.TYPE_VIEW_SELECTED
1507            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1508            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1509            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1510            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1511            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1512            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1513            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
1514
1515    /**
1516     * Temporary Rect currently for use in setBackground().  This will probably
1517     * be extended in the future to hold our own class with more than just
1518     * a Rect. :)
1519     */
1520    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1521
1522    /**
1523     * Temporary flag, used to enable processing of View properties in the native DisplayList
1524     * object instead of during draw(). Soon to be enabled by default for hardware-accelerated
1525     * apps.
1526     * @hide
1527     */
1528    public static final boolean USE_DISPLAY_LIST_PROPERTIES = true;
1529
1530    /**
1531     * Map used to store views' tags.
1532     */
1533    private SparseArray<Object> mKeyedTags;
1534
1535    /**
1536     * The next available accessiiblity id.
1537     */
1538    private static int sNextAccessibilityViewId;
1539
1540    /**
1541     * The animation currently associated with this view.
1542     * @hide
1543     */
1544    protected Animation mCurrentAnimation = null;
1545
1546    /**
1547     * Width as measured during measure pass.
1548     * {@hide}
1549     */
1550    @ViewDebug.ExportedProperty(category = "measurement")
1551    int mMeasuredWidth;
1552
1553    /**
1554     * Height as measured during measure pass.
1555     * {@hide}
1556     */
1557    @ViewDebug.ExportedProperty(category = "measurement")
1558    int mMeasuredHeight;
1559
1560    /**
1561     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1562     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1563     * its display list. This flag, used only when hw accelerated, allows us to clear the
1564     * flag while retaining this information until it's needed (at getDisplayList() time and
1565     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1566     *
1567     * {@hide}
1568     */
1569    boolean mRecreateDisplayList = false;
1570
1571    /**
1572     * The view's identifier.
1573     * {@hide}
1574     *
1575     * @see #setId(int)
1576     * @see #getId()
1577     */
1578    @ViewDebug.ExportedProperty(resolveId = true)
1579    int mID = NO_ID;
1580
1581    /**
1582     * The stable ID of this view for accessibility purposes.
1583     */
1584    int mAccessibilityViewId = NO_ID;
1585
1586    /**
1587     * The view's tag.
1588     * {@hide}
1589     *
1590     * @see #setTag(Object)
1591     * @see #getTag()
1592     */
1593    protected Object mTag;
1594
1595    // for mPrivateFlags:
1596    /** {@hide} */
1597    static final int WANTS_FOCUS                    = 0x00000001;
1598    /** {@hide} */
1599    static final int FOCUSED                        = 0x00000002;
1600    /** {@hide} */
1601    static final int SELECTED                       = 0x00000004;
1602    /** {@hide} */
1603    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1604    /** {@hide} */
1605    static final int HAS_BOUNDS                     = 0x00000010;
1606    /** {@hide} */
1607    static final int DRAWN                          = 0x00000020;
1608    /**
1609     * When this flag is set, this view is running an animation on behalf of its
1610     * children and should therefore not cancel invalidate requests, even if they
1611     * lie outside of this view's bounds.
1612     *
1613     * {@hide}
1614     */
1615    static final int DRAW_ANIMATION                 = 0x00000040;
1616    /** {@hide} */
1617    static final int SKIP_DRAW                      = 0x00000080;
1618    /** {@hide} */
1619    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1620    /** {@hide} */
1621    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1622    /** {@hide} */
1623    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1624    /** {@hide} */
1625    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1626    /** {@hide} */
1627    static final int FORCE_LAYOUT                   = 0x00001000;
1628    /** {@hide} */
1629    static final int LAYOUT_REQUIRED                = 0x00002000;
1630
1631    private static final int PRESSED                = 0x00004000;
1632
1633    /** {@hide} */
1634    static final int DRAWING_CACHE_VALID            = 0x00008000;
1635    /**
1636     * Flag used to indicate that this view should be drawn once more (and only once
1637     * more) after its animation has completed.
1638     * {@hide}
1639     */
1640    static final int ANIMATION_STARTED              = 0x00010000;
1641
1642    private static final int SAVE_STATE_CALLED      = 0x00020000;
1643
1644    /**
1645     * Indicates that the View returned true when onSetAlpha() was called and that
1646     * the alpha must be restored.
1647     * {@hide}
1648     */
1649    static final int ALPHA_SET                      = 0x00040000;
1650
1651    /**
1652     * Set by {@link #setScrollContainer(boolean)}.
1653     */
1654    static final int SCROLL_CONTAINER               = 0x00080000;
1655
1656    /**
1657     * Set by {@link #setScrollContainer(boolean)}.
1658     */
1659    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1660
1661    /**
1662     * View flag indicating whether this view was invalidated (fully or partially.)
1663     *
1664     * @hide
1665     */
1666    static final int DIRTY                          = 0x00200000;
1667
1668    /**
1669     * View flag indicating whether this view was invalidated by an opaque
1670     * invalidate request.
1671     *
1672     * @hide
1673     */
1674    static final int DIRTY_OPAQUE                   = 0x00400000;
1675
1676    /**
1677     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1678     *
1679     * @hide
1680     */
1681    static final int DIRTY_MASK                     = 0x00600000;
1682
1683    /**
1684     * Indicates whether the background is opaque.
1685     *
1686     * @hide
1687     */
1688    static final int OPAQUE_BACKGROUND              = 0x00800000;
1689
1690    /**
1691     * Indicates whether the scrollbars are opaque.
1692     *
1693     * @hide
1694     */
1695    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1696
1697    /**
1698     * Indicates whether the view is opaque.
1699     *
1700     * @hide
1701     */
1702    static final int OPAQUE_MASK                    = 0x01800000;
1703
1704    /**
1705     * Indicates a prepressed state;
1706     * the short time between ACTION_DOWN and recognizing
1707     * a 'real' press. Prepressed is used to recognize quick taps
1708     * even when they are shorter than ViewConfiguration.getTapTimeout().
1709     *
1710     * @hide
1711     */
1712    private static final int PREPRESSED             = 0x02000000;
1713
1714    /**
1715     * Indicates whether the view is temporarily detached.
1716     *
1717     * @hide
1718     */
1719    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1720
1721    /**
1722     * Indicates that we should awaken scroll bars once attached
1723     *
1724     * @hide
1725     */
1726    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1727
1728    /**
1729     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1730     * @hide
1731     */
1732    private static final int HOVERED              = 0x10000000;
1733
1734    /**
1735     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1736     * for transform operations
1737     *
1738     * @hide
1739     */
1740    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1741
1742    /** {@hide} */
1743    static final int ACTIVATED                    = 0x40000000;
1744
1745    /**
1746     * Indicates that this view was specifically invalidated, not just dirtied because some
1747     * child view was invalidated. The flag is used to determine when we need to recreate
1748     * a view's display list (as opposed to just returning a reference to its existing
1749     * display list).
1750     *
1751     * @hide
1752     */
1753    static final int INVALIDATED                  = 0x80000000;
1754
1755    /* Masks for mPrivateFlags2 */
1756
1757    /**
1758     * Indicates that this view has reported that it can accept the current drag's content.
1759     * Cleared when the drag operation concludes.
1760     * @hide
1761     */
1762    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1763
1764    /**
1765     * Indicates that this view is currently directly under the drag location in a
1766     * drag-and-drop operation involving content that it can accept.  Cleared when
1767     * the drag exits the view, or when the drag operation concludes.
1768     * @hide
1769     */
1770    static final int DRAG_HOVERED                 = 0x00000002;
1771
1772    /**
1773     * Horizontal layout direction of this view is from Left to Right.
1774     * Use with {@link #setLayoutDirection}.
1775     */
1776    public static final int LAYOUT_DIRECTION_LTR = 0;
1777
1778    /**
1779     * Horizontal layout direction of this view is from Right to Left.
1780     * Use with {@link #setLayoutDirection}.
1781     */
1782    public static final int LAYOUT_DIRECTION_RTL = 1;
1783
1784    /**
1785     * Horizontal layout direction of this view is inherited from its parent.
1786     * Use with {@link #setLayoutDirection}.
1787     */
1788    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1789
1790    /**
1791     * Horizontal layout direction of this view is from deduced from the default language
1792     * script for the locale. Use with {@link #setLayoutDirection}.
1793     */
1794    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1795
1796    /**
1797     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1798     * @hide
1799     */
1800    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1801
1802    /**
1803     * Mask for use with private flags indicating bits used for horizontal layout direction.
1804     * @hide
1805     */
1806    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1807
1808    /**
1809     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1810     * right-to-left direction.
1811     * @hide
1812     */
1813    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1814
1815    /**
1816     * Indicates whether the view horizontal layout direction has been resolved.
1817     * @hide
1818     */
1819    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1820
1821    /**
1822     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1823     * @hide
1824     */
1825    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1826
1827    /*
1828     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1829     * flag value.
1830     * @hide
1831     */
1832    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1833            LAYOUT_DIRECTION_LTR,
1834            LAYOUT_DIRECTION_RTL,
1835            LAYOUT_DIRECTION_INHERIT,
1836            LAYOUT_DIRECTION_LOCALE
1837    };
1838
1839    /**
1840     * Default horizontal layout direction.
1841     * @hide
1842     */
1843    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1844
1845    /**
1846     * Indicates that the view is tracking some sort of transient state
1847     * that the app should not need to be aware of, but that the framework
1848     * should take special care to preserve.
1849     *
1850     * @hide
1851     */
1852    static final int HAS_TRANSIENT_STATE = 0x00000100;
1853
1854
1855    /**
1856     * Text direction is inherited thru {@link ViewGroup}
1857     */
1858    public static final int TEXT_DIRECTION_INHERIT = 0;
1859
1860    /**
1861     * Text direction is using "first strong algorithm". The first strong directional character
1862     * determines the paragraph direction. If there is no strong directional character, the
1863     * paragraph direction is the view's resolved layout direction.
1864     */
1865    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1866
1867    /**
1868     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1869     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1870     * If there are neither, the paragraph direction is the view's resolved layout direction.
1871     */
1872    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1873
1874    /**
1875     * Text direction is forced to LTR.
1876     */
1877    public static final int TEXT_DIRECTION_LTR = 3;
1878
1879    /**
1880     * Text direction is forced to RTL.
1881     */
1882    public static final int TEXT_DIRECTION_RTL = 4;
1883
1884    /**
1885     * Text direction is coming from the system Locale.
1886     */
1887    public static final int TEXT_DIRECTION_LOCALE = 5;
1888
1889    /**
1890     * Default text direction is inherited
1891     */
1892    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1893
1894    /**
1895     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1896     * @hide
1897     */
1898    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1899
1900    /**
1901     * Mask for use with private flags indicating bits used for text direction.
1902     * @hide
1903     */
1904    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1905
1906    /**
1907     * Array of text direction flags for mapping attribute "textDirection" to correct
1908     * flag value.
1909     * @hide
1910     */
1911    private static final int[] TEXT_DIRECTION_FLAGS = {
1912            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1913            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1914            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1915            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1916            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1917            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1918    };
1919
1920    /**
1921     * Indicates whether the view text direction has been resolved.
1922     * @hide
1923     */
1924    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1925
1926    /**
1927     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1928     * @hide
1929     */
1930    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1931
1932    /**
1933     * Mask for use with private flags indicating bits used for resolved text direction.
1934     * @hide
1935     */
1936    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1937
1938    /**
1939     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1940     * @hide
1941     */
1942    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1943            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1944
1945    /*
1946     * Default text alignment. The text alignment of this View is inherited from its parent.
1947     * Use with {@link #setTextAlignment(int)}
1948     */
1949    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1950
1951    /**
1952     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1953     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1954     *
1955     * Use with {@link #setTextAlignment(int)}
1956     */
1957    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1958
1959    /**
1960     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1961     *
1962     * Use with {@link #setTextAlignment(int)}
1963     */
1964    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1965
1966    /**
1967     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1968     *
1969     * Use with {@link #setTextAlignment(int)}
1970     */
1971    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1972
1973    /**
1974     * Center the paragraph, e.g. ALIGN_CENTER.
1975     *
1976     * Use with {@link #setTextAlignment(int)}
1977     */
1978    public static final int TEXT_ALIGNMENT_CENTER = 4;
1979
1980    /**
1981     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
1982     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
1983     *
1984     * Use with {@link #setTextAlignment(int)}
1985     */
1986    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
1987
1988    /**
1989     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
1990     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
1991     *
1992     * Use with {@link #setTextAlignment(int)}
1993     */
1994    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
1995
1996    /**
1997     * Default text alignment is inherited
1998     */
1999    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2000
2001    /**
2002      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2003      * @hide
2004      */
2005    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2006
2007    /**
2008      * Mask for use with private flags indicating bits used for text alignment.
2009      * @hide
2010      */
2011    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2012
2013    /**
2014     * Array of text direction flags for mapping attribute "textAlignment" to correct
2015     * flag value.
2016     * @hide
2017     */
2018    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2019            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2020            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2021            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2022            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2023            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2024            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2025            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2026    };
2027
2028    /**
2029     * Indicates whether the view text alignment has been resolved.
2030     * @hide
2031     */
2032    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2033
2034    /**
2035     * Bit shift to get the resolved text alignment.
2036     * @hide
2037     */
2038    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2039
2040    /**
2041     * Mask for use with private flags indicating bits used for text alignment.
2042     * @hide
2043     */
2044    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2045
2046    /**
2047     * Indicates whether if the view text alignment has been resolved to gravity
2048     */
2049    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2050            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2051
2052    // Accessiblity constants for mPrivateFlags2
2053
2054    /**
2055     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2056     */
2057    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2058
2059    /**
2060     * Automatically determine whether a view is important for accessibility.
2061     */
2062    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2063
2064    /**
2065     * The view is important for accessibility.
2066     */
2067    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2068
2069    /**
2070     * The view is not important for accessibility.
2071     */
2072    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2073
2074    /**
2075     * The default whether the view is important for accessiblity.
2076     */
2077    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2078
2079    /**
2080     * Mask for obtainig the bits which specify how to determine
2081     * whether a view is important for accessibility.
2082     */
2083    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2084        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2085        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2086
2087    /**
2088     * Flag indicating whether a view has accessibility focus.
2089     */
2090    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2091
2092    /**
2093     * Flag indicating whether a view state for accessibility has changed.
2094     */
2095    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2096
2097    /* End of masks for mPrivateFlags2 */
2098
2099    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2100
2101    /**
2102     * Always allow a user to over-scroll this view, provided it is a
2103     * view that can scroll.
2104     *
2105     * @see #getOverScrollMode()
2106     * @see #setOverScrollMode(int)
2107     */
2108    public static final int OVER_SCROLL_ALWAYS = 0;
2109
2110    /**
2111     * Allow a user to over-scroll this view only if the content is large
2112     * enough to meaningfully scroll, provided it is a view that can scroll.
2113     *
2114     * @see #getOverScrollMode()
2115     * @see #setOverScrollMode(int)
2116     */
2117    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2118
2119    /**
2120     * Never allow a user to over-scroll this view.
2121     *
2122     * @see #getOverScrollMode()
2123     * @see #setOverScrollMode(int)
2124     */
2125    public static final int OVER_SCROLL_NEVER = 2;
2126
2127    /**
2128     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2129     * requested the system UI (status bar) to be visible (the default).
2130     *
2131     * @see #setSystemUiVisibility(int)
2132     */
2133    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2134
2135    /**
2136     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2137     * system UI to enter an unobtrusive "low profile" mode.
2138     *
2139     * <p>This is for use in games, book readers, video players, or any other
2140     * "immersive" application where the usual system chrome is deemed too distracting.
2141     *
2142     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2143     *
2144     * @see #setSystemUiVisibility(int)
2145     */
2146    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2147
2148    /**
2149     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2150     * system navigation be temporarily hidden.
2151     *
2152     * <p>This is an even less obtrusive state than that called for by
2153     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2154     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2155     * those to disappear. This is useful (in conjunction with the
2156     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2157     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2158     * window flags) for displaying content using every last pixel on the display.
2159     *
2160     * <p>There is a limitation: because navigation controls are so important, the least user
2161     * interaction will cause them to reappear immediately.  When this happens, both
2162     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2163     * so that both elements reappear at the same time.
2164     *
2165     * @see #setSystemUiVisibility(int)
2166     */
2167    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2168
2169    /**
2170     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2171     * into the normal fullscreen mode so that its content can take over the screen
2172     * while still allowing the user to interact with the application.
2173     *
2174     * <p>This has the same visual effect as
2175     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2176     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2177     * meaning that non-critical screen decorations (such as the status bar) will be
2178     * hidden while the user is in the View's window, focusing the experience on
2179     * that content.  Unlike the window flag, if you are using ActionBar in
2180     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2181     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2182     * hide the action bar.
2183     *
2184     * <p>This approach to going fullscreen is best used over the window flag when
2185     * it is a transient state -- that is, the application does this at certain
2186     * points in its user interaction where it wants to allow the user to focus
2187     * on content, but not as a continuous state.  For situations where the application
2188     * would like to simply stay full screen the entire time (such as a game that
2189     * wants to take over the screen), the
2190     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2191     * is usually a better approach.  The state set here will be removed by the system
2192     * in various situations (such as the user moving to another application) like
2193     * the other system UI states.
2194     *
2195     * <p>When using this flag, the application should provide some easy facility
2196     * for the user to go out of it.  A common example would be in an e-book
2197     * reader, where tapping on the screen brings back whatever screen and UI
2198     * decorations that had been hidden while the user was immersed in reading
2199     * the book.
2200     *
2201     * @see #setSystemUiVisibility(int)
2202     */
2203    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2204
2205    /**
2206     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2207     * flags, we would like a stable view of the content insets given to
2208     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2209     * will always represent the worst case that the application can expect
2210     * as a continue state.  In practice this means with any of system bar,
2211     * nav bar, and status bar shown, but not the space that would be needed
2212     * for an input method.
2213     *
2214     * <p>If you are using ActionBar in
2215     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2216     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2217     * insets it adds to those given to the application.
2218     */
2219    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2220
2221    /**
2222     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2223     * to be layed out as if it has requested
2224     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2225     * allows it to avoid artifacts when switching in and out of that mode, at
2226     * the expense that some of its user interface may be covered by screen
2227     * decorations when they are shown.  You can perform layout of your inner
2228     * UI elements to account for the navagation system UI through the
2229     * {@link #fitSystemWindows(Rect)} method.
2230     */
2231    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2232
2233    /**
2234     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2235     * to be layed out as if it has requested
2236     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2237     * allows it to avoid artifacts when switching in and out of that mode, at
2238     * the expense that some of its user interface may be covered by screen
2239     * decorations when they are shown.  You can perform layout of your inner
2240     * UI elements to account for non-fullscreen system UI through the
2241     * {@link #fitSystemWindows(Rect)} method.
2242     */
2243    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2244
2245    /**
2246     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2247     */
2248    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2249
2250    /**
2251     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2252     */
2253    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2254
2255    /**
2256     * @hide
2257     *
2258     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2259     * out of the public fields to keep the undefined bits out of the developer's way.
2260     *
2261     * Flag to make the status bar not expandable.  Unless you also
2262     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2263     */
2264    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2265
2266    /**
2267     * @hide
2268     *
2269     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2270     * out of the public fields to keep the undefined bits out of the developer's way.
2271     *
2272     * Flag to hide notification icons and scrolling ticker text.
2273     */
2274    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2275
2276    /**
2277     * @hide
2278     *
2279     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2280     * out of the public fields to keep the undefined bits out of the developer's way.
2281     *
2282     * Flag to disable incoming notification alerts.  This will not block
2283     * icons, but it will block sound, vibrating and other visual or aural notifications.
2284     */
2285    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2286
2287    /**
2288     * @hide
2289     *
2290     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2291     * out of the public fields to keep the undefined bits out of the developer's way.
2292     *
2293     * Flag to hide only the scrolling ticker.  Note that
2294     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2295     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2296     */
2297    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2298
2299    /**
2300     * @hide
2301     *
2302     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2303     * out of the public fields to keep the undefined bits out of the developer's way.
2304     *
2305     * Flag to hide the center system info area.
2306     */
2307    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2308
2309    /**
2310     * @hide
2311     *
2312     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2313     * out of the public fields to keep the undefined bits out of the developer's way.
2314     *
2315     * Flag to hide only the home button.  Don't use this
2316     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2317     */
2318    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2319
2320    /**
2321     * @hide
2322     *
2323     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2324     * out of the public fields to keep the undefined bits out of the developer's way.
2325     *
2326     * Flag to hide only the back button. Don't use this
2327     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2328     */
2329    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2330
2331    /**
2332     * @hide
2333     *
2334     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2335     * out of the public fields to keep the undefined bits out of the developer's way.
2336     *
2337     * Flag to hide only the clock.  You might use this if your activity has
2338     * its own clock making the status bar's clock redundant.
2339     */
2340    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2341
2342    /**
2343     * @hide
2344     *
2345     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2346     * out of the public fields to keep the undefined bits out of the developer's way.
2347     *
2348     * Flag to hide only the recent apps button. Don't use this
2349     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2350     */
2351    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2352
2353    /**
2354     * @hide
2355     */
2356    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2357
2358    /**
2359     * These are the system UI flags that can be cleared by events outside
2360     * of an application.  Currently this is just the ability to tap on the
2361     * screen while hiding the navigation bar to have it return.
2362     * @hide
2363     */
2364    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2365            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2366            | SYSTEM_UI_FLAG_FULLSCREEN;
2367
2368    /**
2369     * Flags that can impact the layout in relation to system UI.
2370     */
2371    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2372            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2373            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2374
2375    /**
2376     * Find views that render the specified text.
2377     *
2378     * @see #findViewsWithText(ArrayList, CharSequence, int)
2379     */
2380    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2381
2382    /**
2383     * Find find views that contain the specified content description.
2384     *
2385     * @see #findViewsWithText(ArrayList, CharSequence, int)
2386     */
2387    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2388
2389    /**
2390     * Find views that contain {@link AccessibilityNodeProvider}. Such
2391     * a View is a root of virtual view hierarchy and may contain the searched
2392     * text. If this flag is set Views with providers are automatically
2393     * added and it is a responsibility of the client to call the APIs of
2394     * the provider to determine whether the virtual tree rooted at this View
2395     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2396     * represeting the virtual views with this text.
2397     *
2398     * @see #findViewsWithText(ArrayList, CharSequence, int)
2399     *
2400     * @hide
2401     */
2402    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2403
2404    /**
2405     * Indicates that the screen has changed state and is now off.
2406     *
2407     * @see #onScreenStateChanged(int)
2408     */
2409    public static final int SCREEN_STATE_OFF = 0x0;
2410
2411    /**
2412     * Indicates that the screen has changed state and is now on.
2413     *
2414     * @see #onScreenStateChanged(int)
2415     */
2416    public static final int SCREEN_STATE_ON = 0x1;
2417
2418    /**
2419     * Controls the over-scroll mode for this view.
2420     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2421     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2422     * and {@link #OVER_SCROLL_NEVER}.
2423     */
2424    private int mOverScrollMode;
2425
2426    /**
2427     * The parent this view is attached to.
2428     * {@hide}
2429     *
2430     * @see #getParent()
2431     */
2432    protected ViewParent mParent;
2433
2434    /**
2435     * {@hide}
2436     */
2437    AttachInfo mAttachInfo;
2438
2439    /**
2440     * {@hide}
2441     */
2442    @ViewDebug.ExportedProperty(flagMapping = {
2443        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2444                name = "FORCE_LAYOUT"),
2445        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2446                name = "LAYOUT_REQUIRED"),
2447        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2448            name = "DRAWING_CACHE_INVALID", outputIf = false),
2449        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2450        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2451        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2452        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2453    })
2454    int mPrivateFlags;
2455    int mPrivateFlags2;
2456
2457    /**
2458     * This view's request for the visibility of the status bar.
2459     * @hide
2460     */
2461    @ViewDebug.ExportedProperty(flagMapping = {
2462        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2463                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2464                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2465        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2466                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2467                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2468        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2469                                equals = SYSTEM_UI_FLAG_VISIBLE,
2470                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2471    })
2472    int mSystemUiVisibility;
2473
2474    /**
2475     * Count of how many windows this view has been attached to.
2476     */
2477    int mWindowAttachCount;
2478
2479    /**
2480     * The layout parameters associated with this view and used by the parent
2481     * {@link android.view.ViewGroup} to determine how this view should be
2482     * laid out.
2483     * {@hide}
2484     */
2485    protected ViewGroup.LayoutParams mLayoutParams;
2486
2487    /**
2488     * The view flags hold various views states.
2489     * {@hide}
2490     */
2491    @ViewDebug.ExportedProperty
2492    int mViewFlags;
2493
2494    static class TransformationInfo {
2495        /**
2496         * The transform matrix for the View. This transform is calculated internally
2497         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2498         * is used by default. Do *not* use this variable directly; instead call
2499         * getMatrix(), which will automatically recalculate the matrix if necessary
2500         * to get the correct matrix based on the latest rotation and scale properties.
2501         */
2502        private final Matrix mMatrix = new Matrix();
2503
2504        /**
2505         * The transform matrix for the View. This transform is calculated internally
2506         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2507         * is used by default. Do *not* use this variable directly; instead call
2508         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2509         * to get the correct matrix based on the latest rotation and scale properties.
2510         */
2511        private Matrix mInverseMatrix;
2512
2513        /**
2514         * An internal variable that tracks whether we need to recalculate the
2515         * transform matrix, based on whether the rotation or scaleX/Y properties
2516         * have changed since the matrix was last calculated.
2517         */
2518        boolean mMatrixDirty = false;
2519
2520        /**
2521         * An internal variable that tracks whether we need to recalculate the
2522         * transform matrix, based on whether the rotation or scaleX/Y properties
2523         * have changed since the matrix was last calculated.
2524         */
2525        private boolean mInverseMatrixDirty = true;
2526
2527        /**
2528         * A variable that tracks whether we need to recalculate the
2529         * transform matrix, based on whether the rotation or scaleX/Y properties
2530         * have changed since the matrix was last calculated. This variable
2531         * is only valid after a call to updateMatrix() or to a function that
2532         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2533         */
2534        private boolean mMatrixIsIdentity = true;
2535
2536        /**
2537         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2538         */
2539        private Camera mCamera = null;
2540
2541        /**
2542         * This matrix is used when computing the matrix for 3D rotations.
2543         */
2544        private Matrix matrix3D = null;
2545
2546        /**
2547         * These prev values are used to recalculate a centered pivot point when necessary. The
2548         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2549         * set), so thes values are only used then as well.
2550         */
2551        private int mPrevWidth = -1;
2552        private int mPrevHeight = -1;
2553
2554        /**
2555         * The degrees rotation around the vertical axis through the pivot point.
2556         */
2557        @ViewDebug.ExportedProperty
2558        float mRotationY = 0f;
2559
2560        /**
2561         * The degrees rotation around the horizontal axis through the pivot point.
2562         */
2563        @ViewDebug.ExportedProperty
2564        float mRotationX = 0f;
2565
2566        /**
2567         * The degrees rotation around the pivot point.
2568         */
2569        @ViewDebug.ExportedProperty
2570        float mRotation = 0f;
2571
2572        /**
2573         * The amount of translation of the object away from its left property (post-layout).
2574         */
2575        @ViewDebug.ExportedProperty
2576        float mTranslationX = 0f;
2577
2578        /**
2579         * The amount of translation of the object away from its top property (post-layout).
2580         */
2581        @ViewDebug.ExportedProperty
2582        float mTranslationY = 0f;
2583
2584        /**
2585         * The amount of scale in the x direction around the pivot point. A
2586         * value of 1 means no scaling is applied.
2587         */
2588        @ViewDebug.ExportedProperty
2589        float mScaleX = 1f;
2590
2591        /**
2592         * The amount of scale in the y direction around the pivot point. A
2593         * value of 1 means no scaling is applied.
2594         */
2595        @ViewDebug.ExportedProperty
2596        float mScaleY = 1f;
2597
2598        /**
2599         * The x location of the point around which the view is rotated and scaled.
2600         */
2601        @ViewDebug.ExportedProperty
2602        float mPivotX = 0f;
2603
2604        /**
2605         * The y location of the point around which the view is rotated and scaled.
2606         */
2607        @ViewDebug.ExportedProperty
2608        float mPivotY = 0f;
2609
2610        /**
2611         * The opacity of the View. This is a value from 0 to 1, where 0 means
2612         * completely transparent and 1 means completely opaque.
2613         */
2614        @ViewDebug.ExportedProperty
2615        float mAlpha = 1f;
2616    }
2617
2618    TransformationInfo mTransformationInfo;
2619
2620    private boolean mLastIsOpaque;
2621
2622    /**
2623     * Convenience value to check for float values that are close enough to zero to be considered
2624     * zero.
2625     */
2626    private static final float NONZERO_EPSILON = .001f;
2627
2628    /**
2629     * The distance in pixels from the left edge of this view's parent
2630     * to the left edge of this view.
2631     * {@hide}
2632     */
2633    @ViewDebug.ExportedProperty(category = "layout")
2634    protected int mLeft;
2635    /**
2636     * The distance in pixels from the left edge of this view's parent
2637     * to the right edge of this view.
2638     * {@hide}
2639     */
2640    @ViewDebug.ExportedProperty(category = "layout")
2641    protected int mRight;
2642    /**
2643     * The distance in pixels from the top edge of this view's parent
2644     * to the top edge of this view.
2645     * {@hide}
2646     */
2647    @ViewDebug.ExportedProperty(category = "layout")
2648    protected int mTop;
2649    /**
2650     * The distance in pixels from the top edge of this view's parent
2651     * to the bottom edge of this view.
2652     * {@hide}
2653     */
2654    @ViewDebug.ExportedProperty(category = "layout")
2655    protected int mBottom;
2656
2657    /**
2658     * The offset, in pixels, by which the content of this view is scrolled
2659     * horizontally.
2660     * {@hide}
2661     */
2662    @ViewDebug.ExportedProperty(category = "scrolling")
2663    protected int mScrollX;
2664    /**
2665     * The offset, in pixels, by which the content of this view is scrolled
2666     * vertically.
2667     * {@hide}
2668     */
2669    @ViewDebug.ExportedProperty(category = "scrolling")
2670    protected int mScrollY;
2671
2672    /**
2673     * The left padding in pixels, that is the distance in pixels between the
2674     * left edge of this view and the left edge of its content.
2675     * {@hide}
2676     */
2677    @ViewDebug.ExportedProperty(category = "padding")
2678    protected int mPaddingLeft;
2679    /**
2680     * The right padding in pixels, that is the distance in pixels between the
2681     * right edge of this view and the right edge of its content.
2682     * {@hide}
2683     */
2684    @ViewDebug.ExportedProperty(category = "padding")
2685    protected int mPaddingRight;
2686    /**
2687     * The top padding in pixels, that is the distance in pixels between the
2688     * top edge of this view and the top edge of its content.
2689     * {@hide}
2690     */
2691    @ViewDebug.ExportedProperty(category = "padding")
2692    protected int mPaddingTop;
2693    /**
2694     * The bottom padding in pixels, that is the distance in pixels between the
2695     * bottom edge of this view and the bottom edge of its content.
2696     * {@hide}
2697     */
2698    @ViewDebug.ExportedProperty(category = "padding")
2699    protected int mPaddingBottom;
2700
2701    /**
2702     * The layout insets in pixels, that is the distance in pixels between the
2703     * visible edges of this view its bounds.
2704     */
2705    private Insets mLayoutInsets;
2706
2707    /**
2708     * Briefly describes the view and is primarily used for accessibility support.
2709     */
2710    private CharSequence mContentDescription;
2711
2712    /**
2713     * Cache the paddingRight set by the user to append to the scrollbar's size.
2714     *
2715     * @hide
2716     */
2717    @ViewDebug.ExportedProperty(category = "padding")
2718    protected int mUserPaddingRight;
2719
2720    /**
2721     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2722     *
2723     * @hide
2724     */
2725    @ViewDebug.ExportedProperty(category = "padding")
2726    protected int mUserPaddingBottom;
2727
2728    /**
2729     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2730     *
2731     * @hide
2732     */
2733    @ViewDebug.ExportedProperty(category = "padding")
2734    protected int mUserPaddingLeft;
2735
2736    /**
2737     * Cache if the user padding is relative.
2738     *
2739     */
2740    @ViewDebug.ExportedProperty(category = "padding")
2741    boolean mUserPaddingRelative;
2742
2743    /**
2744     * Cache the paddingStart set by the user to append to the scrollbar's size.
2745     *
2746     */
2747    @ViewDebug.ExportedProperty(category = "padding")
2748    int mUserPaddingStart;
2749
2750    /**
2751     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2752     *
2753     */
2754    @ViewDebug.ExportedProperty(category = "padding")
2755    int mUserPaddingEnd;
2756
2757    /**
2758     * @hide
2759     */
2760    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2761    /**
2762     * @hide
2763     */
2764    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2765
2766    private Drawable mBackground;
2767
2768    private int mBackgroundResource;
2769    private boolean mBackgroundSizeChanged;
2770
2771    static class ListenerInfo {
2772        /**
2773         * Listener used to dispatch focus change events.
2774         * This field should be made private, so it is hidden from the SDK.
2775         * {@hide}
2776         */
2777        protected OnFocusChangeListener mOnFocusChangeListener;
2778
2779        /**
2780         * Listeners for layout change events.
2781         */
2782        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2783
2784        /**
2785         * Listeners for attach events.
2786         */
2787        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2788
2789        /**
2790         * Listener used to dispatch click events.
2791         * This field should be made private, so it is hidden from the SDK.
2792         * {@hide}
2793         */
2794        public OnClickListener mOnClickListener;
2795
2796        /**
2797         * Listener used to dispatch long click events.
2798         * This field should be made private, so it is hidden from the SDK.
2799         * {@hide}
2800         */
2801        protected OnLongClickListener mOnLongClickListener;
2802
2803        /**
2804         * Listener used to build the context menu.
2805         * This field should be made private, so it is hidden from the SDK.
2806         * {@hide}
2807         */
2808        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2809
2810        private OnKeyListener mOnKeyListener;
2811
2812        private OnTouchListener mOnTouchListener;
2813
2814        private OnHoverListener mOnHoverListener;
2815
2816        private OnGenericMotionListener mOnGenericMotionListener;
2817
2818        private OnDragListener mOnDragListener;
2819
2820        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2821    }
2822
2823    ListenerInfo mListenerInfo;
2824
2825    /**
2826     * The application environment this view lives in.
2827     * This field should be made private, so it is hidden from the SDK.
2828     * {@hide}
2829     */
2830    protected Context mContext;
2831
2832    private final Resources mResources;
2833
2834    private ScrollabilityCache mScrollCache;
2835
2836    private int[] mDrawableState = null;
2837
2838    /**
2839     * Set to true when drawing cache is enabled and cannot be created.
2840     *
2841     * @hide
2842     */
2843    public boolean mCachingFailed;
2844
2845    private Bitmap mDrawingCache;
2846    private Bitmap mUnscaledDrawingCache;
2847    private HardwareLayer mHardwareLayer;
2848    DisplayList mDisplayList;
2849
2850    /**
2851     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2852     * the user may specify which view to go to next.
2853     */
2854    private int mNextFocusLeftId = View.NO_ID;
2855
2856    /**
2857     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2858     * the user may specify which view to go to next.
2859     */
2860    private int mNextFocusRightId = View.NO_ID;
2861
2862    /**
2863     * When this view has focus and the next focus is {@link #FOCUS_UP},
2864     * the user may specify which view to go to next.
2865     */
2866    private int mNextFocusUpId = View.NO_ID;
2867
2868    /**
2869     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2870     * the user may specify which view to go to next.
2871     */
2872    private int mNextFocusDownId = View.NO_ID;
2873
2874    /**
2875     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2876     * the user may specify which view to go to next.
2877     */
2878    int mNextFocusForwardId = View.NO_ID;
2879
2880    private CheckForLongPress mPendingCheckForLongPress;
2881    private CheckForTap mPendingCheckForTap = null;
2882    private PerformClick mPerformClick;
2883    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2884
2885    private UnsetPressedState mUnsetPressedState;
2886
2887    /**
2888     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2889     * up event while a long press is invoked as soon as the long press duration is reached, so
2890     * a long press could be performed before the tap is checked, in which case the tap's action
2891     * should not be invoked.
2892     */
2893    private boolean mHasPerformedLongPress;
2894
2895    /**
2896     * The minimum height of the view. We'll try our best to have the height
2897     * of this view to at least this amount.
2898     */
2899    @ViewDebug.ExportedProperty(category = "measurement")
2900    private int mMinHeight;
2901
2902    /**
2903     * The minimum width of the view. We'll try our best to have the width
2904     * of this view to at least this amount.
2905     */
2906    @ViewDebug.ExportedProperty(category = "measurement")
2907    private int mMinWidth;
2908
2909    /**
2910     * The delegate to handle touch events that are physically in this view
2911     * but should be handled by another view.
2912     */
2913    private TouchDelegate mTouchDelegate = null;
2914
2915    /**
2916     * Solid color to use as a background when creating the drawing cache. Enables
2917     * the cache to use 16 bit bitmaps instead of 32 bit.
2918     */
2919    private int mDrawingCacheBackgroundColor = 0;
2920
2921    /**
2922     * Special tree observer used when mAttachInfo is null.
2923     */
2924    private ViewTreeObserver mFloatingTreeObserver;
2925
2926    /**
2927     * Cache the touch slop from the context that created the view.
2928     */
2929    private int mTouchSlop;
2930
2931    /**
2932     * Object that handles automatic animation of view properties.
2933     */
2934    private ViewPropertyAnimator mAnimator = null;
2935
2936    /**
2937     * Flag indicating that a drag can cross window boundaries.  When
2938     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2939     * with this flag set, all visible applications will be able to participate
2940     * in the drag operation and receive the dragged content.
2941     *
2942     * @hide
2943     */
2944    public static final int DRAG_FLAG_GLOBAL = 1;
2945
2946    /**
2947     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2948     */
2949    private float mVerticalScrollFactor;
2950
2951    /**
2952     * Position of the vertical scroll bar.
2953     */
2954    private int mVerticalScrollbarPosition;
2955
2956    /**
2957     * Position the scroll bar at the default position as determined by the system.
2958     */
2959    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2960
2961    /**
2962     * Position the scroll bar along the left edge.
2963     */
2964    public static final int SCROLLBAR_POSITION_LEFT = 1;
2965
2966    /**
2967     * Position the scroll bar along the right edge.
2968     */
2969    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2970
2971    /**
2972     * Indicates that the view does not have a layer.
2973     *
2974     * @see #getLayerType()
2975     * @see #setLayerType(int, android.graphics.Paint)
2976     * @see #LAYER_TYPE_SOFTWARE
2977     * @see #LAYER_TYPE_HARDWARE
2978     */
2979    public static final int LAYER_TYPE_NONE = 0;
2980
2981    /**
2982     * <p>Indicates that the view has a software layer. A software layer is backed
2983     * by a bitmap and causes the view to be rendered using Android's software
2984     * rendering pipeline, even if hardware acceleration is enabled.</p>
2985     *
2986     * <p>Software layers have various usages:</p>
2987     * <p>When the application is not using hardware acceleration, a software layer
2988     * is useful to apply a specific color filter and/or blending mode and/or
2989     * translucency to a view and all its children.</p>
2990     * <p>When the application is using hardware acceleration, a software layer
2991     * is useful to render drawing primitives not supported by the hardware
2992     * accelerated pipeline. It can also be used to cache a complex view tree
2993     * into a texture and reduce the complexity of drawing operations. For instance,
2994     * when animating a complex view tree with a translation, a software layer can
2995     * be used to render the view tree only once.</p>
2996     * <p>Software layers should be avoided when the affected view tree updates
2997     * often. Every update will require to re-render the software layer, which can
2998     * potentially be slow (particularly when hardware acceleration is turned on
2999     * since the layer will have to be uploaded into a hardware texture after every
3000     * update.)</p>
3001     *
3002     * @see #getLayerType()
3003     * @see #setLayerType(int, android.graphics.Paint)
3004     * @see #LAYER_TYPE_NONE
3005     * @see #LAYER_TYPE_HARDWARE
3006     */
3007    public static final int LAYER_TYPE_SOFTWARE = 1;
3008
3009    /**
3010     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3011     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3012     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3013     * rendering pipeline, but only if hardware acceleration is turned on for the
3014     * view hierarchy. When hardware acceleration is turned off, hardware layers
3015     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3016     *
3017     * <p>A hardware layer is useful to apply a specific color filter and/or
3018     * blending mode and/or translucency to a view and all its children.</p>
3019     * <p>A hardware layer can be used to cache a complex view tree into a
3020     * texture and reduce the complexity of drawing operations. For instance,
3021     * when animating a complex view tree with a translation, a hardware layer can
3022     * be used to render the view tree only once.</p>
3023     * <p>A hardware layer can also be used to increase the rendering quality when
3024     * rotation transformations are applied on a view. It can also be used to
3025     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3026     *
3027     * @see #getLayerType()
3028     * @see #setLayerType(int, android.graphics.Paint)
3029     * @see #LAYER_TYPE_NONE
3030     * @see #LAYER_TYPE_SOFTWARE
3031     */
3032    public static final int LAYER_TYPE_HARDWARE = 2;
3033
3034    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3035            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3036            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3037            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3038    })
3039    int mLayerType = LAYER_TYPE_NONE;
3040    Paint mLayerPaint;
3041    Rect mLocalDirtyRect;
3042
3043    /**
3044     * Set to true when the view is sending hover accessibility events because it
3045     * is the innermost hovered view.
3046     */
3047    private boolean mSendingHoverAccessibilityEvents;
3048
3049    /**
3050     * Simple constructor to use when creating a view from code.
3051     *
3052     * @param context The Context the view is running in, through which it can
3053     *        access the current theme, resources, etc.
3054     */
3055    public View(Context context) {
3056        mContext = context;
3057        mResources = context != null ? context.getResources() : null;
3058        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3059        // Set layout and text direction defaults
3060        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3061                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3062                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3063                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3064        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3065        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3066        mUserPaddingStart = -1;
3067        mUserPaddingEnd = -1;
3068        mUserPaddingRelative = false;
3069    }
3070
3071    /**
3072     * Delegate for injecting accessiblity functionality.
3073     */
3074    AccessibilityDelegate mAccessibilityDelegate;
3075
3076    /**
3077     * Consistency verifier for debugging purposes.
3078     * @hide
3079     */
3080    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3081            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3082                    new InputEventConsistencyVerifier(this, 0) : null;
3083
3084    /**
3085     * Constructor that is called when inflating a view from XML. This is called
3086     * when a view is being constructed from an XML file, supplying attributes
3087     * that were specified in the XML file. This version uses a default style of
3088     * 0, so the only attribute values applied are those in the Context's Theme
3089     * and the given AttributeSet.
3090     *
3091     * <p>
3092     * The method onFinishInflate() will be called after all children have been
3093     * added.
3094     *
3095     * @param context The Context the view is running in, through which it can
3096     *        access the current theme, resources, etc.
3097     * @param attrs The attributes of the XML tag that is inflating the view.
3098     * @see #View(Context, AttributeSet, int)
3099     */
3100    public View(Context context, AttributeSet attrs) {
3101        this(context, attrs, 0);
3102    }
3103
3104    /**
3105     * Perform inflation from XML and apply a class-specific base style. This
3106     * constructor of View allows subclasses to use their own base style when
3107     * they are inflating. For example, a Button class's constructor would call
3108     * this version of the super class constructor and supply
3109     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3110     * the theme's button style to modify all of the base view attributes (in
3111     * particular its background) as well as the Button class's attributes.
3112     *
3113     * @param context The Context the view is running in, through which it can
3114     *        access the current theme, resources, etc.
3115     * @param attrs The attributes of the XML tag that is inflating the view.
3116     * @param defStyle The default style to apply to this view. If 0, no style
3117     *        will be applied (beyond what is included in the theme). This may
3118     *        either be an attribute resource, whose value will be retrieved
3119     *        from the current theme, or an explicit style resource.
3120     * @see #View(Context, AttributeSet)
3121     */
3122    public View(Context context, AttributeSet attrs, int defStyle) {
3123        this(context);
3124
3125        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3126                defStyle, 0);
3127
3128        Drawable background = null;
3129
3130        int leftPadding = -1;
3131        int topPadding = -1;
3132        int rightPadding = -1;
3133        int bottomPadding = -1;
3134        int startPadding = -1;
3135        int endPadding = -1;
3136
3137        int padding = -1;
3138
3139        int viewFlagValues = 0;
3140        int viewFlagMasks = 0;
3141
3142        boolean setScrollContainer = false;
3143
3144        int x = 0;
3145        int y = 0;
3146
3147        float tx = 0;
3148        float ty = 0;
3149        float rotation = 0;
3150        float rotationX = 0;
3151        float rotationY = 0;
3152        float sx = 1f;
3153        float sy = 1f;
3154        boolean transformSet = false;
3155
3156        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3157
3158        int overScrollMode = mOverScrollMode;
3159        final int N = a.getIndexCount();
3160        for (int i = 0; i < N; i++) {
3161            int attr = a.getIndex(i);
3162            switch (attr) {
3163                case com.android.internal.R.styleable.View_background:
3164                    background = a.getDrawable(attr);
3165                    break;
3166                case com.android.internal.R.styleable.View_padding:
3167                    padding = a.getDimensionPixelSize(attr, -1);
3168                    break;
3169                 case com.android.internal.R.styleable.View_paddingLeft:
3170                    leftPadding = a.getDimensionPixelSize(attr, -1);
3171                    break;
3172                case com.android.internal.R.styleable.View_paddingTop:
3173                    topPadding = a.getDimensionPixelSize(attr, -1);
3174                    break;
3175                case com.android.internal.R.styleable.View_paddingRight:
3176                    rightPadding = a.getDimensionPixelSize(attr, -1);
3177                    break;
3178                case com.android.internal.R.styleable.View_paddingBottom:
3179                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3180                    break;
3181                case com.android.internal.R.styleable.View_paddingStart:
3182                    startPadding = a.getDimensionPixelSize(attr, -1);
3183                    break;
3184                case com.android.internal.R.styleable.View_paddingEnd:
3185                    endPadding = a.getDimensionPixelSize(attr, -1);
3186                    break;
3187                case com.android.internal.R.styleable.View_scrollX:
3188                    x = a.getDimensionPixelOffset(attr, 0);
3189                    break;
3190                case com.android.internal.R.styleable.View_scrollY:
3191                    y = a.getDimensionPixelOffset(attr, 0);
3192                    break;
3193                case com.android.internal.R.styleable.View_alpha:
3194                    setAlpha(a.getFloat(attr, 1f));
3195                    break;
3196                case com.android.internal.R.styleable.View_transformPivotX:
3197                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3198                    break;
3199                case com.android.internal.R.styleable.View_transformPivotY:
3200                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3201                    break;
3202                case com.android.internal.R.styleable.View_translationX:
3203                    tx = a.getDimensionPixelOffset(attr, 0);
3204                    transformSet = true;
3205                    break;
3206                case com.android.internal.R.styleable.View_translationY:
3207                    ty = a.getDimensionPixelOffset(attr, 0);
3208                    transformSet = true;
3209                    break;
3210                case com.android.internal.R.styleable.View_rotation:
3211                    rotation = a.getFloat(attr, 0);
3212                    transformSet = true;
3213                    break;
3214                case com.android.internal.R.styleable.View_rotationX:
3215                    rotationX = a.getFloat(attr, 0);
3216                    transformSet = true;
3217                    break;
3218                case com.android.internal.R.styleable.View_rotationY:
3219                    rotationY = a.getFloat(attr, 0);
3220                    transformSet = true;
3221                    break;
3222                case com.android.internal.R.styleable.View_scaleX:
3223                    sx = a.getFloat(attr, 1f);
3224                    transformSet = true;
3225                    break;
3226                case com.android.internal.R.styleable.View_scaleY:
3227                    sy = a.getFloat(attr, 1f);
3228                    transformSet = true;
3229                    break;
3230                case com.android.internal.R.styleable.View_id:
3231                    mID = a.getResourceId(attr, NO_ID);
3232                    break;
3233                case com.android.internal.R.styleable.View_tag:
3234                    mTag = a.getText(attr);
3235                    break;
3236                case com.android.internal.R.styleable.View_fitsSystemWindows:
3237                    if (a.getBoolean(attr, false)) {
3238                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3239                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3240                    }
3241                    break;
3242                case com.android.internal.R.styleable.View_focusable:
3243                    if (a.getBoolean(attr, false)) {
3244                        viewFlagValues |= FOCUSABLE;
3245                        viewFlagMasks |= FOCUSABLE_MASK;
3246                    }
3247                    break;
3248                case com.android.internal.R.styleable.View_focusableInTouchMode:
3249                    if (a.getBoolean(attr, false)) {
3250                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3251                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3252                    }
3253                    break;
3254                case com.android.internal.R.styleable.View_clickable:
3255                    if (a.getBoolean(attr, false)) {
3256                        viewFlagValues |= CLICKABLE;
3257                        viewFlagMasks |= CLICKABLE;
3258                    }
3259                    break;
3260                case com.android.internal.R.styleable.View_longClickable:
3261                    if (a.getBoolean(attr, false)) {
3262                        viewFlagValues |= LONG_CLICKABLE;
3263                        viewFlagMasks |= LONG_CLICKABLE;
3264                    }
3265                    break;
3266                case com.android.internal.R.styleable.View_saveEnabled:
3267                    if (!a.getBoolean(attr, true)) {
3268                        viewFlagValues |= SAVE_DISABLED;
3269                        viewFlagMasks |= SAVE_DISABLED_MASK;
3270                    }
3271                    break;
3272                case com.android.internal.R.styleable.View_duplicateParentState:
3273                    if (a.getBoolean(attr, false)) {
3274                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3275                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3276                    }
3277                    break;
3278                case com.android.internal.R.styleable.View_visibility:
3279                    final int visibility = a.getInt(attr, 0);
3280                    if (visibility != 0) {
3281                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3282                        viewFlagMasks |= VISIBILITY_MASK;
3283                    }
3284                    break;
3285                case com.android.internal.R.styleable.View_layoutDirection:
3286                    // Clear any layout direction flags (included resolved bits) already set
3287                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3288                    // Set the layout direction flags depending on the value of the attribute
3289                    final int layoutDirection = a.getInt(attr, -1);
3290                    final int value = (layoutDirection != -1) ?
3291                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3292                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3293                    break;
3294                case com.android.internal.R.styleable.View_drawingCacheQuality:
3295                    final int cacheQuality = a.getInt(attr, 0);
3296                    if (cacheQuality != 0) {
3297                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3298                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3299                    }
3300                    break;
3301                case com.android.internal.R.styleable.View_contentDescription:
3302                    mContentDescription = a.getString(attr);
3303                    break;
3304                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3305                    if (!a.getBoolean(attr, true)) {
3306                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3307                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3308                    }
3309                    break;
3310                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3311                    if (!a.getBoolean(attr, true)) {
3312                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3313                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3314                    }
3315                    break;
3316                case R.styleable.View_scrollbars:
3317                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3318                    if (scrollbars != SCROLLBARS_NONE) {
3319                        viewFlagValues |= scrollbars;
3320                        viewFlagMasks |= SCROLLBARS_MASK;
3321                        initializeScrollbars(a);
3322                    }
3323                    break;
3324                //noinspection deprecation
3325                case R.styleable.View_fadingEdge:
3326                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3327                        // Ignore the attribute starting with ICS
3328                        break;
3329                    }
3330                    // With builds < ICS, fall through and apply fading edges
3331                case R.styleable.View_requiresFadingEdge:
3332                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3333                    if (fadingEdge != FADING_EDGE_NONE) {
3334                        viewFlagValues |= fadingEdge;
3335                        viewFlagMasks |= FADING_EDGE_MASK;
3336                        initializeFadingEdge(a);
3337                    }
3338                    break;
3339                case R.styleable.View_scrollbarStyle:
3340                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3341                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3342                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3343                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3344                    }
3345                    break;
3346                case R.styleable.View_isScrollContainer:
3347                    setScrollContainer = true;
3348                    if (a.getBoolean(attr, false)) {
3349                        setScrollContainer(true);
3350                    }
3351                    break;
3352                case com.android.internal.R.styleable.View_keepScreenOn:
3353                    if (a.getBoolean(attr, false)) {
3354                        viewFlagValues |= KEEP_SCREEN_ON;
3355                        viewFlagMasks |= KEEP_SCREEN_ON;
3356                    }
3357                    break;
3358                case R.styleable.View_filterTouchesWhenObscured:
3359                    if (a.getBoolean(attr, false)) {
3360                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3361                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3362                    }
3363                    break;
3364                case R.styleable.View_nextFocusLeft:
3365                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3366                    break;
3367                case R.styleable.View_nextFocusRight:
3368                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3369                    break;
3370                case R.styleable.View_nextFocusUp:
3371                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3372                    break;
3373                case R.styleable.View_nextFocusDown:
3374                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3375                    break;
3376                case R.styleable.View_nextFocusForward:
3377                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3378                    break;
3379                case R.styleable.View_minWidth:
3380                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3381                    break;
3382                case R.styleable.View_minHeight:
3383                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3384                    break;
3385                case R.styleable.View_onClick:
3386                    if (context.isRestricted()) {
3387                        throw new IllegalStateException("The android:onClick attribute cannot "
3388                                + "be used within a restricted context");
3389                    }
3390
3391                    final String handlerName = a.getString(attr);
3392                    if (handlerName != null) {
3393                        setOnClickListener(new OnClickListener() {
3394                            private Method mHandler;
3395
3396                            public void onClick(View v) {
3397                                if (mHandler == null) {
3398                                    try {
3399                                        mHandler = getContext().getClass().getMethod(handlerName,
3400                                                View.class);
3401                                    } catch (NoSuchMethodException e) {
3402                                        int id = getId();
3403                                        String idText = id == NO_ID ? "" : " with id '"
3404                                                + getContext().getResources().getResourceEntryName(
3405                                                    id) + "'";
3406                                        throw new IllegalStateException("Could not find a method " +
3407                                                handlerName + "(View) in the activity "
3408                                                + getContext().getClass() + " for onClick handler"
3409                                                + " on view " + View.this.getClass() + idText, e);
3410                                    }
3411                                }
3412
3413                                try {
3414                                    mHandler.invoke(getContext(), View.this);
3415                                } catch (IllegalAccessException e) {
3416                                    throw new IllegalStateException("Could not execute non "
3417                                            + "public method of the activity", e);
3418                                } catch (InvocationTargetException e) {
3419                                    throw new IllegalStateException("Could not execute "
3420                                            + "method of the activity", e);
3421                                }
3422                            }
3423                        });
3424                    }
3425                    break;
3426                case R.styleable.View_overScrollMode:
3427                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3428                    break;
3429                case R.styleable.View_verticalScrollbarPosition:
3430                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3431                    break;
3432                case R.styleable.View_layerType:
3433                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3434                    break;
3435                case R.styleable.View_textDirection:
3436                    // Clear any text direction flag already set
3437                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3438                    // Set the text direction flags depending on the value of the attribute
3439                    final int textDirection = a.getInt(attr, -1);
3440                    if (textDirection != -1) {
3441                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3442                    }
3443                    break;
3444                case R.styleable.View_textAlignment:
3445                    // Clear any text alignment flag already set
3446                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3447                    // Set the text alignment flag depending on the value of the attribute
3448                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3449                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3450                    break;
3451                case R.styleable.View_importantForAccessibility:
3452                    setImportantForAccessibility(a.getInt(attr,
3453                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3454            }
3455        }
3456
3457        a.recycle();
3458
3459        setOverScrollMode(overScrollMode);
3460
3461        if (background != null) {
3462            setBackground(background);
3463        }
3464
3465        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3466        // layout direction). Those cached values will be used later during padding resolution.
3467        mUserPaddingStart = startPadding;
3468        mUserPaddingEnd = endPadding;
3469
3470        updateUserPaddingRelative();
3471
3472        if (padding >= 0) {
3473            leftPadding = padding;
3474            topPadding = padding;
3475            rightPadding = padding;
3476            bottomPadding = padding;
3477        }
3478
3479        // If the user specified the padding (either with android:padding or
3480        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3481        // use the default padding or the padding from the background drawable
3482        // (stored at this point in mPadding*)
3483        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3484                topPadding >= 0 ? topPadding : mPaddingTop,
3485                rightPadding >= 0 ? rightPadding : mPaddingRight,
3486                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3487
3488        if (viewFlagMasks != 0) {
3489            setFlags(viewFlagValues, viewFlagMasks);
3490        }
3491
3492        // Needs to be called after mViewFlags is set
3493        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3494            recomputePadding();
3495        }
3496
3497        if (x != 0 || y != 0) {
3498            scrollTo(x, y);
3499        }
3500
3501        if (transformSet) {
3502            setTranslationX(tx);
3503            setTranslationY(ty);
3504            setRotation(rotation);
3505            setRotationX(rotationX);
3506            setRotationY(rotationY);
3507            setScaleX(sx);
3508            setScaleY(sy);
3509        }
3510
3511        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3512            setScrollContainer(true);
3513        }
3514
3515        computeOpaqueFlags();
3516    }
3517
3518    private void updateUserPaddingRelative() {
3519        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3520    }
3521
3522    /**
3523     * Non-public constructor for use in testing
3524     */
3525    View() {
3526        mResources = null;
3527    }
3528
3529    /**
3530     * <p>
3531     * Initializes the fading edges from a given set of styled attributes. This
3532     * method should be called by subclasses that need fading edges and when an
3533     * instance of these subclasses is created programmatically rather than
3534     * being inflated from XML. This method is automatically called when the XML
3535     * is inflated.
3536     * </p>
3537     *
3538     * @param a the styled attributes set to initialize the fading edges from
3539     */
3540    protected void initializeFadingEdge(TypedArray a) {
3541        initScrollCache();
3542
3543        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3544                R.styleable.View_fadingEdgeLength,
3545                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3546    }
3547
3548    /**
3549     * Returns the size of the vertical faded edges used to indicate that more
3550     * content in this view is visible.
3551     *
3552     * @return The size in pixels of the vertical faded edge or 0 if vertical
3553     *         faded edges are not enabled for this view.
3554     * @attr ref android.R.styleable#View_fadingEdgeLength
3555     */
3556    public int getVerticalFadingEdgeLength() {
3557        if (isVerticalFadingEdgeEnabled()) {
3558            ScrollabilityCache cache = mScrollCache;
3559            if (cache != null) {
3560                return cache.fadingEdgeLength;
3561            }
3562        }
3563        return 0;
3564    }
3565
3566    /**
3567     * Set the size of the faded edge used to indicate that more content in this
3568     * view is available.  Will not change whether the fading edge is enabled; use
3569     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3570     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3571     * for the vertical or horizontal fading edges.
3572     *
3573     * @param length The size in pixels of the faded edge used to indicate that more
3574     *        content in this view is visible.
3575     */
3576    public void setFadingEdgeLength(int length) {
3577        initScrollCache();
3578        mScrollCache.fadingEdgeLength = length;
3579    }
3580
3581    /**
3582     * Returns the size of the horizontal faded edges used to indicate that more
3583     * content in this view is visible.
3584     *
3585     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3586     *         faded edges are not enabled for this view.
3587     * @attr ref android.R.styleable#View_fadingEdgeLength
3588     */
3589    public int getHorizontalFadingEdgeLength() {
3590        if (isHorizontalFadingEdgeEnabled()) {
3591            ScrollabilityCache cache = mScrollCache;
3592            if (cache != null) {
3593                return cache.fadingEdgeLength;
3594            }
3595        }
3596        return 0;
3597    }
3598
3599    /**
3600     * Returns the width of the vertical scrollbar.
3601     *
3602     * @return The width in pixels of the vertical scrollbar or 0 if there
3603     *         is no vertical scrollbar.
3604     */
3605    public int getVerticalScrollbarWidth() {
3606        ScrollabilityCache cache = mScrollCache;
3607        if (cache != null) {
3608            ScrollBarDrawable scrollBar = cache.scrollBar;
3609            if (scrollBar != null) {
3610                int size = scrollBar.getSize(true);
3611                if (size <= 0) {
3612                    size = cache.scrollBarSize;
3613                }
3614                return size;
3615            }
3616            return 0;
3617        }
3618        return 0;
3619    }
3620
3621    /**
3622     * Returns the height of the horizontal scrollbar.
3623     *
3624     * @return The height in pixels of the horizontal scrollbar or 0 if
3625     *         there is no horizontal scrollbar.
3626     */
3627    protected int getHorizontalScrollbarHeight() {
3628        ScrollabilityCache cache = mScrollCache;
3629        if (cache != null) {
3630            ScrollBarDrawable scrollBar = cache.scrollBar;
3631            if (scrollBar != null) {
3632                int size = scrollBar.getSize(false);
3633                if (size <= 0) {
3634                    size = cache.scrollBarSize;
3635                }
3636                return size;
3637            }
3638            return 0;
3639        }
3640        return 0;
3641    }
3642
3643    /**
3644     * <p>
3645     * Initializes the scrollbars from a given set of styled attributes. This
3646     * method should be called by subclasses that need scrollbars and when an
3647     * instance of these subclasses is created programmatically rather than
3648     * being inflated from XML. This method is automatically called when the XML
3649     * is inflated.
3650     * </p>
3651     *
3652     * @param a the styled attributes set to initialize the scrollbars from
3653     */
3654    protected void initializeScrollbars(TypedArray a) {
3655        initScrollCache();
3656
3657        final ScrollabilityCache scrollabilityCache = mScrollCache;
3658
3659        if (scrollabilityCache.scrollBar == null) {
3660            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3661        }
3662
3663        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3664
3665        if (!fadeScrollbars) {
3666            scrollabilityCache.state = ScrollabilityCache.ON;
3667        }
3668        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3669
3670
3671        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3672                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3673                        .getScrollBarFadeDuration());
3674        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3675                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3676                ViewConfiguration.getScrollDefaultDelay());
3677
3678
3679        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3680                com.android.internal.R.styleable.View_scrollbarSize,
3681                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3682
3683        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3684        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3685
3686        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3687        if (thumb != null) {
3688            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3689        }
3690
3691        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3692                false);
3693        if (alwaysDraw) {
3694            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3695        }
3696
3697        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3698        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3699
3700        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3701        if (thumb != null) {
3702            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3703        }
3704
3705        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3706                false);
3707        if (alwaysDraw) {
3708            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3709        }
3710
3711        // Re-apply user/background padding so that scrollbar(s) get added
3712        resolvePadding();
3713    }
3714
3715    /**
3716     * <p>
3717     * Initalizes the scrollability cache if necessary.
3718     * </p>
3719     */
3720    private void initScrollCache() {
3721        if (mScrollCache == null) {
3722            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3723        }
3724    }
3725
3726    private ScrollabilityCache getScrollCache() {
3727        initScrollCache();
3728        return mScrollCache;
3729    }
3730
3731    /**
3732     * Set the position of the vertical scroll bar. Should be one of
3733     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3734     * {@link #SCROLLBAR_POSITION_RIGHT}.
3735     *
3736     * @param position Where the vertical scroll bar should be positioned.
3737     */
3738    public void setVerticalScrollbarPosition(int position) {
3739        if (mVerticalScrollbarPosition != position) {
3740            mVerticalScrollbarPosition = position;
3741            computeOpaqueFlags();
3742            resolvePadding();
3743        }
3744    }
3745
3746    /**
3747     * @return The position where the vertical scroll bar will show, if applicable.
3748     * @see #setVerticalScrollbarPosition(int)
3749     */
3750    public int getVerticalScrollbarPosition() {
3751        return mVerticalScrollbarPosition;
3752    }
3753
3754    ListenerInfo getListenerInfo() {
3755        if (mListenerInfo != null) {
3756            return mListenerInfo;
3757        }
3758        mListenerInfo = new ListenerInfo();
3759        return mListenerInfo;
3760    }
3761
3762    /**
3763     * Register a callback to be invoked when focus of this view changed.
3764     *
3765     * @param l The callback that will run.
3766     */
3767    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3768        getListenerInfo().mOnFocusChangeListener = l;
3769    }
3770
3771    /**
3772     * Add a listener that will be called when the bounds of the view change due to
3773     * layout processing.
3774     *
3775     * @param listener The listener that will be called when layout bounds change.
3776     */
3777    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3778        ListenerInfo li = getListenerInfo();
3779        if (li.mOnLayoutChangeListeners == null) {
3780            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3781        }
3782        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3783            li.mOnLayoutChangeListeners.add(listener);
3784        }
3785    }
3786
3787    /**
3788     * Remove a listener for layout changes.
3789     *
3790     * @param listener The listener for layout bounds change.
3791     */
3792    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3793        ListenerInfo li = mListenerInfo;
3794        if (li == null || li.mOnLayoutChangeListeners == null) {
3795            return;
3796        }
3797        li.mOnLayoutChangeListeners.remove(listener);
3798    }
3799
3800    /**
3801     * Add a listener for attach state changes.
3802     *
3803     * This listener will be called whenever this view is attached or detached
3804     * from a window. Remove the listener using
3805     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3806     *
3807     * @param listener Listener to attach
3808     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3809     */
3810    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3811        ListenerInfo li = getListenerInfo();
3812        if (li.mOnAttachStateChangeListeners == null) {
3813            li.mOnAttachStateChangeListeners
3814                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3815        }
3816        li.mOnAttachStateChangeListeners.add(listener);
3817    }
3818
3819    /**
3820     * Remove a listener for attach state changes. The listener will receive no further
3821     * notification of window attach/detach events.
3822     *
3823     * @param listener Listener to remove
3824     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3825     */
3826    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3827        ListenerInfo li = mListenerInfo;
3828        if (li == null || li.mOnAttachStateChangeListeners == null) {
3829            return;
3830        }
3831        li.mOnAttachStateChangeListeners.remove(listener);
3832    }
3833
3834    /**
3835     * Returns the focus-change callback registered for this view.
3836     *
3837     * @return The callback, or null if one is not registered.
3838     */
3839    public OnFocusChangeListener getOnFocusChangeListener() {
3840        ListenerInfo li = mListenerInfo;
3841        return li != null ? li.mOnFocusChangeListener : null;
3842    }
3843
3844    /**
3845     * Register a callback to be invoked when this view is clicked. If this view is not
3846     * clickable, it becomes clickable.
3847     *
3848     * @param l The callback that will run
3849     *
3850     * @see #setClickable(boolean)
3851     */
3852    public void setOnClickListener(OnClickListener l) {
3853        if (!isClickable()) {
3854            setClickable(true);
3855        }
3856        getListenerInfo().mOnClickListener = l;
3857    }
3858
3859    /**
3860     * Return whether this view has an attached OnClickListener.  Returns
3861     * true if there is a listener, false if there is none.
3862     */
3863    public boolean hasOnClickListeners() {
3864        ListenerInfo li = mListenerInfo;
3865        return (li != null && li.mOnClickListener != null);
3866    }
3867
3868    /**
3869     * Register a callback to be invoked when this view is clicked and held. If this view is not
3870     * long clickable, it becomes long clickable.
3871     *
3872     * @param l The callback that will run
3873     *
3874     * @see #setLongClickable(boolean)
3875     */
3876    public void setOnLongClickListener(OnLongClickListener l) {
3877        if (!isLongClickable()) {
3878            setLongClickable(true);
3879        }
3880        getListenerInfo().mOnLongClickListener = l;
3881    }
3882
3883    /**
3884     * Register a callback to be invoked when the context menu for this view is
3885     * being built. If this view is not long clickable, it becomes long clickable.
3886     *
3887     * @param l The callback that will run
3888     *
3889     */
3890    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3891        if (!isLongClickable()) {
3892            setLongClickable(true);
3893        }
3894        getListenerInfo().mOnCreateContextMenuListener = l;
3895    }
3896
3897    /**
3898     * Call this view's OnClickListener, if it is defined.  Performs all normal
3899     * actions associated with clicking: reporting accessibility event, playing
3900     * a sound, etc.
3901     *
3902     * @return True there was an assigned OnClickListener that was called, false
3903     *         otherwise is returned.
3904     */
3905    public boolean performClick() {
3906        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3907
3908        ListenerInfo li = mListenerInfo;
3909        if (li != null && li.mOnClickListener != null) {
3910            playSoundEffect(SoundEffectConstants.CLICK);
3911            li.mOnClickListener.onClick(this);
3912            return true;
3913        }
3914
3915        return false;
3916    }
3917
3918    /**
3919     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3920     * this only calls the listener, and does not do any associated clicking
3921     * actions like reporting an accessibility event.
3922     *
3923     * @return True there was an assigned OnClickListener that was called, false
3924     *         otherwise is returned.
3925     */
3926    public boolean callOnClick() {
3927        ListenerInfo li = mListenerInfo;
3928        if (li != null && li.mOnClickListener != null) {
3929            li.mOnClickListener.onClick(this);
3930            return true;
3931        }
3932        return false;
3933    }
3934
3935    /**
3936     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3937     * OnLongClickListener did not consume the event.
3938     *
3939     * @return True if one of the above receivers consumed the event, false otherwise.
3940     */
3941    public boolean performLongClick() {
3942        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3943
3944        boolean handled = false;
3945        ListenerInfo li = mListenerInfo;
3946        if (li != null && li.mOnLongClickListener != null) {
3947            handled = li.mOnLongClickListener.onLongClick(View.this);
3948        }
3949        if (!handled) {
3950            handled = showContextMenu();
3951        }
3952        if (handled) {
3953            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3954        }
3955        return handled;
3956    }
3957
3958    /**
3959     * Performs button-related actions during a touch down event.
3960     *
3961     * @param event The event.
3962     * @return True if the down was consumed.
3963     *
3964     * @hide
3965     */
3966    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3967        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3968            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3969                return true;
3970            }
3971        }
3972        return false;
3973    }
3974
3975    /**
3976     * Bring up the context menu for this view.
3977     *
3978     * @return Whether a context menu was displayed.
3979     */
3980    public boolean showContextMenu() {
3981        return getParent().showContextMenuForChild(this);
3982    }
3983
3984    /**
3985     * Bring up the context menu for this view, referring to the item under the specified point.
3986     *
3987     * @param x The referenced x coordinate.
3988     * @param y The referenced y coordinate.
3989     * @param metaState The keyboard modifiers that were pressed.
3990     * @return Whether a context menu was displayed.
3991     *
3992     * @hide
3993     */
3994    public boolean showContextMenu(float x, float y, int metaState) {
3995        return showContextMenu();
3996    }
3997
3998    /**
3999     * Start an action mode.
4000     *
4001     * @param callback Callback that will control the lifecycle of the action mode
4002     * @return The new action mode if it is started, null otherwise
4003     *
4004     * @see ActionMode
4005     */
4006    public ActionMode startActionMode(ActionMode.Callback callback) {
4007        ViewParent parent = getParent();
4008        if (parent == null) return null;
4009        return parent.startActionModeForChild(this, callback);
4010    }
4011
4012    /**
4013     * Register a callback to be invoked when a key is pressed in this view.
4014     * @param l the key listener to attach to this view
4015     */
4016    public void setOnKeyListener(OnKeyListener l) {
4017        getListenerInfo().mOnKeyListener = l;
4018    }
4019
4020    /**
4021     * Register a callback to be invoked when a touch event is sent to this view.
4022     * @param l the touch listener to attach to this view
4023     */
4024    public void setOnTouchListener(OnTouchListener l) {
4025        getListenerInfo().mOnTouchListener = l;
4026    }
4027
4028    /**
4029     * Register a callback to be invoked when a generic motion event is sent to this view.
4030     * @param l the generic motion listener to attach to this view
4031     */
4032    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4033        getListenerInfo().mOnGenericMotionListener = l;
4034    }
4035
4036    /**
4037     * Register a callback to be invoked when a hover event is sent to this view.
4038     * @param l the hover listener to attach to this view
4039     */
4040    public void setOnHoverListener(OnHoverListener l) {
4041        getListenerInfo().mOnHoverListener = l;
4042    }
4043
4044    /**
4045     * Register a drag event listener callback object for this View. The parameter is
4046     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4047     * View, the system calls the
4048     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4049     * @param l An implementation of {@link android.view.View.OnDragListener}.
4050     */
4051    public void setOnDragListener(OnDragListener l) {
4052        getListenerInfo().mOnDragListener = l;
4053    }
4054
4055    /**
4056     * Give this view focus. This will cause
4057     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4058     *
4059     * Note: this does not check whether this {@link View} should get focus, it just
4060     * gives it focus no matter what.  It should only be called internally by framework
4061     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4062     *
4063     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4064     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4065     *        focus moved when requestFocus() is called. It may not always
4066     *        apply, in which case use the default View.FOCUS_DOWN.
4067     * @param previouslyFocusedRect The rectangle of the view that had focus
4068     *        prior in this View's coordinate system.
4069     */
4070    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4071        if (DBG) {
4072            System.out.println(this + " requestFocus()");
4073        }
4074
4075        if ((mPrivateFlags & FOCUSED) == 0) {
4076            mPrivateFlags |= FOCUSED;
4077
4078            if (mParent != null) {
4079                mParent.requestChildFocus(this, this);
4080            }
4081
4082            onFocusChanged(true, direction, previouslyFocusedRect);
4083            refreshDrawableState();
4084
4085            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4086                notifyAccessibilityStateChanged();
4087            }
4088        }
4089    }
4090
4091    /**
4092     * Request that a rectangle of this view be visible on the screen,
4093     * scrolling if necessary just enough.
4094     *
4095     * <p>A View should call this if it maintains some notion of which part
4096     * of its content is interesting.  For example, a text editing view
4097     * should call this when its cursor moves.
4098     *
4099     * @param rectangle The rectangle.
4100     * @return Whether any parent scrolled.
4101     */
4102    public boolean requestRectangleOnScreen(Rect rectangle) {
4103        return requestRectangleOnScreen(rectangle, false);
4104    }
4105
4106    /**
4107     * Request that a rectangle of this view be visible on the screen,
4108     * scrolling if necessary just enough.
4109     *
4110     * <p>A View should call this if it maintains some notion of which part
4111     * of its content is interesting.  For example, a text editing view
4112     * should call this when its cursor moves.
4113     *
4114     * <p>When <code>immediate</code> is set to true, scrolling will not be
4115     * animated.
4116     *
4117     * @param rectangle The rectangle.
4118     * @param immediate True to forbid animated scrolling, false otherwise
4119     * @return Whether any parent scrolled.
4120     */
4121    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4122        View child = this;
4123        ViewParent parent = mParent;
4124        boolean scrolled = false;
4125        while (parent != null) {
4126            scrolled |= parent.requestChildRectangleOnScreen(child,
4127                    rectangle, immediate);
4128
4129            // offset rect so next call has the rectangle in the
4130            // coordinate system of its direct child.
4131            rectangle.offset(child.getLeft(), child.getTop());
4132            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4133
4134            if (!(parent instanceof View)) {
4135                break;
4136            }
4137
4138            child = (View) parent;
4139            parent = child.getParent();
4140        }
4141        return scrolled;
4142    }
4143
4144    /**
4145     * Called when this view wants to give up focus. If focus is cleared
4146     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4147     * <p>
4148     * <strong>Note:</strong> When a View clears focus the framework is trying
4149     * to give focus to the first focusable View from the top. Hence, if this
4150     * View is the first from the top that can take focus, then all callbacks
4151     * related to clearing focus will be invoked after wich the framework will
4152     * give focus to this view.
4153     * </p>
4154     */
4155    public void clearFocus() {
4156        if (DBG) {
4157            System.out.println(this + " clearFocus()");
4158        }
4159
4160        if ((mPrivateFlags & FOCUSED) != 0) {
4161            mPrivateFlags &= ~FOCUSED;
4162
4163            if (mParent != null) {
4164                mParent.clearChildFocus(this);
4165            }
4166
4167            onFocusChanged(false, 0, null);
4168
4169            refreshDrawableState();
4170
4171            ensureInputFocusOnFirstFocusable();
4172
4173            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4174                notifyAccessibilityStateChanged();
4175            }
4176        }
4177    }
4178
4179    void ensureInputFocusOnFirstFocusable() {
4180        View root = getRootView();
4181        if (root != null) {
4182            root.requestFocus();
4183        }
4184    }
4185
4186    /**
4187     * Called internally by the view system when a new view is getting focus.
4188     * This is what clears the old focus.
4189     */
4190    void unFocus() {
4191        if (DBG) {
4192            System.out.println(this + " unFocus()");
4193        }
4194
4195        if ((mPrivateFlags & FOCUSED) != 0) {
4196            mPrivateFlags &= ~FOCUSED;
4197
4198            onFocusChanged(false, 0, null);
4199            refreshDrawableState();
4200
4201            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4202                notifyAccessibilityStateChanged();
4203            }
4204        }
4205    }
4206
4207    /**
4208     * Returns true if this view has focus iteself, or is the ancestor of the
4209     * view that has focus.
4210     *
4211     * @return True if this view has or contains focus, false otherwise.
4212     */
4213    @ViewDebug.ExportedProperty(category = "focus")
4214    public boolean hasFocus() {
4215        return (mPrivateFlags & FOCUSED) != 0;
4216    }
4217
4218    /**
4219     * Returns true if this view is focusable or if it contains a reachable View
4220     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4221     * is a View whose parents do not block descendants focus.
4222     *
4223     * Only {@link #VISIBLE} views are considered focusable.
4224     *
4225     * @return True if the view is focusable or if the view contains a focusable
4226     *         View, false otherwise.
4227     *
4228     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4229     */
4230    public boolean hasFocusable() {
4231        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4232    }
4233
4234    /**
4235     * Called by the view system when the focus state of this view changes.
4236     * When the focus change event is caused by directional navigation, direction
4237     * and previouslyFocusedRect provide insight into where the focus is coming from.
4238     * When overriding, be sure to call up through to the super class so that
4239     * the standard focus handling will occur.
4240     *
4241     * @param gainFocus True if the View has focus; false otherwise.
4242     * @param direction The direction focus has moved when requestFocus()
4243     *                  is called to give this view focus. Values are
4244     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4245     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4246     *                  It may not always apply, in which case use the default.
4247     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4248     *        system, of the previously focused view.  If applicable, this will be
4249     *        passed in as finer grained information about where the focus is coming
4250     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4251     */
4252    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4253        if (gainFocus) {
4254            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4255                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4256                requestAccessibilityFocus();
4257            }
4258        }
4259
4260        InputMethodManager imm = InputMethodManager.peekInstance();
4261        if (!gainFocus) {
4262            if (isPressed()) {
4263                setPressed(false);
4264            }
4265            if (imm != null && mAttachInfo != null
4266                    && mAttachInfo.mHasWindowFocus) {
4267                imm.focusOut(this);
4268            }
4269            onFocusLost();
4270        } else if (imm != null && mAttachInfo != null
4271                && mAttachInfo.mHasWindowFocus) {
4272            imm.focusIn(this);
4273        }
4274
4275        invalidate(true);
4276        ListenerInfo li = mListenerInfo;
4277        if (li != null && li.mOnFocusChangeListener != null) {
4278            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4279        }
4280
4281        if (mAttachInfo != null) {
4282            mAttachInfo.mKeyDispatchState.reset(this);
4283        }
4284    }
4285
4286    /**
4287     * Sends an accessibility event of the given type. If accessiiblity is
4288     * not enabled this method has no effect. The default implementation calls
4289     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4290     * to populate information about the event source (this View), then calls
4291     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4292     * populate the text content of the event source including its descendants,
4293     * and last calls
4294     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4295     * on its parent to resuest sending of the event to interested parties.
4296     * <p>
4297     * If an {@link AccessibilityDelegate} has been specified via calling
4298     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4299     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4300     * responsible for handling this call.
4301     * </p>
4302     *
4303     * @param eventType The type of the event to send, as defined by several types from
4304     * {@link android.view.accessibility.AccessibilityEvent}, such as
4305     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4306     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4307     *
4308     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4309     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4310     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4311     * @see AccessibilityDelegate
4312     */
4313    public void sendAccessibilityEvent(int eventType) {
4314        if (mAccessibilityDelegate != null) {
4315            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4316        } else {
4317            sendAccessibilityEventInternal(eventType);
4318        }
4319    }
4320
4321    /**
4322     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4323     * {@link AccessibilityEvent} to make an announcement which is related to some
4324     * sort of a context change for which none of the events representing UI transitions
4325     * is a good fit. For example, announcing a new page in a book. If accessibility
4326     * is not enabled this method does nothing.
4327     *
4328     * @param text The announcement text.
4329     */
4330    public void announceForAccessibility(CharSequence text) {
4331        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4332            AccessibilityEvent event = AccessibilityEvent.obtain(
4333                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4334            event.getText().add(text);
4335            sendAccessibilityEventUnchecked(event);
4336        }
4337    }
4338
4339    /**
4340     * @see #sendAccessibilityEvent(int)
4341     *
4342     * Note: Called from the default {@link AccessibilityDelegate}.
4343     */
4344    void sendAccessibilityEventInternal(int eventType) {
4345        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4346            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4347        }
4348    }
4349
4350    /**
4351     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4352     * takes as an argument an empty {@link AccessibilityEvent} and does not
4353     * perform a check whether accessibility is enabled.
4354     * <p>
4355     * If an {@link AccessibilityDelegate} has been specified via calling
4356     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4357     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4358     * is responsible for handling this call.
4359     * </p>
4360     *
4361     * @param event The event to send.
4362     *
4363     * @see #sendAccessibilityEvent(int)
4364     */
4365    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4366        if (mAccessibilityDelegate != null) {
4367            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4368        } else {
4369            sendAccessibilityEventUncheckedInternal(event);
4370        }
4371    }
4372
4373    /**
4374     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4375     *
4376     * Note: Called from the default {@link AccessibilityDelegate}.
4377     */
4378    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4379        if (!isShown()) {
4380            return;
4381        }
4382        onInitializeAccessibilityEvent(event);
4383        // Only a subset of accessibility events populates text content.
4384        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4385            dispatchPopulateAccessibilityEvent(event);
4386        }
4387        // Intercept accessibility focus events fired by virtual nodes to keep
4388        // track of accessibility focus position in such nodes.
4389        final int eventType = event.getEventType();
4390        switch (eventType) {
4391            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4392                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4393                        event.getSourceNodeId());
4394                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4395                    ViewRootImpl viewRootImpl = getViewRootImpl();
4396                    if (viewRootImpl != null) {
4397                        viewRootImpl.setAccessibilityFocusedHost(this);
4398                    }
4399                }
4400            } break;
4401            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4402                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4403                        event.getSourceNodeId());
4404                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4405                    ViewRootImpl viewRootImpl = getViewRootImpl();
4406                    if (viewRootImpl != null) {
4407                        viewRootImpl.setAccessibilityFocusedHost(null);
4408                    }
4409                }
4410            } break;
4411        }
4412        // In the beginning we called #isShown(), so we know that getParent() is not null.
4413        getParent().requestSendAccessibilityEvent(this, event);
4414    }
4415
4416    /**
4417     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4418     * to its children for adding their text content to the event. Note that the
4419     * event text is populated in a separate dispatch path since we add to the
4420     * event not only the text of the source but also the text of all its descendants.
4421     * A typical implementation will call
4422     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4423     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4424     * on each child. Override this method if custom population of the event text
4425     * content is required.
4426     * <p>
4427     * If an {@link AccessibilityDelegate} has been specified via calling
4428     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4429     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4430     * is responsible for handling this call.
4431     * </p>
4432     * <p>
4433     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4434     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4435     * </p>
4436     *
4437     * @param event The event.
4438     *
4439     * @return True if the event population was completed.
4440     */
4441    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4442        if (mAccessibilityDelegate != null) {
4443            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4444        } else {
4445            return dispatchPopulateAccessibilityEventInternal(event);
4446        }
4447    }
4448
4449    /**
4450     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4451     *
4452     * Note: Called from the default {@link AccessibilityDelegate}.
4453     */
4454    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4455        onPopulateAccessibilityEvent(event);
4456        return false;
4457    }
4458
4459    /**
4460     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4461     * giving a chance to this View to populate the accessibility event with its
4462     * text content. While this method is free to modify event
4463     * attributes other than text content, doing so should normally be performed in
4464     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4465     * <p>
4466     * Example: Adding formatted date string to an accessibility event in addition
4467     *          to the text added by the super implementation:
4468     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4469     *     super.onPopulateAccessibilityEvent(event);
4470     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4471     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4472     *         mCurrentDate.getTimeInMillis(), flags);
4473     *     event.getText().add(selectedDateUtterance);
4474     * }</pre>
4475     * <p>
4476     * If an {@link AccessibilityDelegate} has been specified via calling
4477     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4478     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4479     * is responsible for handling this call.
4480     * </p>
4481     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4482     * information to the event, in case the default implementation has basic information to add.
4483     * </p>
4484     *
4485     * @param event The accessibility event which to populate.
4486     *
4487     * @see #sendAccessibilityEvent(int)
4488     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4489     */
4490    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4491        if (mAccessibilityDelegate != null) {
4492            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4493        } else {
4494            onPopulateAccessibilityEventInternal(event);
4495        }
4496    }
4497
4498    /**
4499     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4500     *
4501     * Note: Called from the default {@link AccessibilityDelegate}.
4502     */
4503    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4504
4505    }
4506
4507    /**
4508     * Initializes an {@link AccessibilityEvent} with information about
4509     * this View which is the event source. In other words, the source of
4510     * an accessibility event is the view whose state change triggered firing
4511     * the event.
4512     * <p>
4513     * Example: Setting the password property of an event in addition
4514     *          to properties set by the super implementation:
4515     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4516     *     super.onInitializeAccessibilityEvent(event);
4517     *     event.setPassword(true);
4518     * }</pre>
4519     * <p>
4520     * If an {@link AccessibilityDelegate} has been specified via calling
4521     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4522     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4523     * is responsible for handling this call.
4524     * </p>
4525     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4526     * information to the event, in case the default implementation has basic information to add.
4527     * </p>
4528     * @param event The event to initialize.
4529     *
4530     * @see #sendAccessibilityEvent(int)
4531     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4532     */
4533    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4534        if (mAccessibilityDelegate != null) {
4535            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4536        } else {
4537            onInitializeAccessibilityEventInternal(event);
4538        }
4539    }
4540
4541    /**
4542     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4543     *
4544     * Note: Called from the default {@link AccessibilityDelegate}.
4545     */
4546    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4547        event.setSource(this);
4548        event.setClassName(View.class.getName());
4549        event.setPackageName(getContext().getPackageName());
4550        event.setEnabled(isEnabled());
4551        event.setContentDescription(mContentDescription);
4552
4553        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4554            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4555            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4556                    FOCUSABLES_ALL);
4557            event.setItemCount(focusablesTempList.size());
4558            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4559            focusablesTempList.clear();
4560        }
4561    }
4562
4563    /**
4564     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4565     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4566     * This method is responsible for obtaining an accessibility node info from a
4567     * pool of reusable instances and calling
4568     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4569     * initialize the former.
4570     * <p>
4571     * Note: The client is responsible for recycling the obtained instance by calling
4572     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4573     * </p>
4574     *
4575     * @return A populated {@link AccessibilityNodeInfo}.
4576     *
4577     * @see AccessibilityNodeInfo
4578     */
4579    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4580        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4581        if (provider != null) {
4582            return provider.createAccessibilityNodeInfo(View.NO_ID);
4583        } else {
4584            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4585            onInitializeAccessibilityNodeInfo(info);
4586            return info;
4587        }
4588    }
4589
4590    /**
4591     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4592     * The base implementation sets:
4593     * <ul>
4594     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4595     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4596     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4597     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4598     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4599     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4600     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4601     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4602     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4603     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4604     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4605     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4606     * </ul>
4607     * <p>
4608     * Subclasses should override this method, call the super implementation,
4609     * and set additional attributes.
4610     * </p>
4611     * <p>
4612     * If an {@link AccessibilityDelegate} has been specified via calling
4613     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4614     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4615     * is responsible for handling this call.
4616     * </p>
4617     *
4618     * @param info The instance to initialize.
4619     */
4620    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4621        if (mAccessibilityDelegate != null) {
4622            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4623        } else {
4624            onInitializeAccessibilityNodeInfoInternal(info);
4625        }
4626    }
4627
4628    /**
4629     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4630     *
4631     * Note: Called from the default {@link AccessibilityDelegate}.
4632     */
4633    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4634        Rect bounds = mAttachInfo.mTmpInvalRect;
4635        getDrawingRect(bounds);
4636        info.setBoundsInParent(bounds);
4637
4638        getGlobalVisibleRect(bounds);
4639        bounds.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4640        info.setBoundsInScreen(bounds);
4641
4642        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4643            ViewParent parent = getParentForAccessibility();
4644            if (parent instanceof View) {
4645                info.setParent((View) parent);
4646            }
4647        }
4648
4649        info.setPackageName(mContext.getPackageName());
4650        info.setClassName(View.class.getName());
4651        info.setContentDescription(getContentDescription());
4652
4653        info.setEnabled(isEnabled());
4654        info.setClickable(isClickable());
4655        info.setFocusable(isFocusable());
4656        info.setFocused(isFocused());
4657        info.setAccessibilityFocused(isAccessibilityFocused());
4658        info.setSelected(isSelected());
4659        info.setLongClickable(isLongClickable());
4660
4661        // TODO: These make sense only if we are in an AdapterView but all
4662        // views can be selected. Maybe from accessiiblity perspective
4663        // we should report as selectable view in an AdapterView.
4664        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4665        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4666
4667        if (isFocusable()) {
4668            if (isFocused()) {
4669                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4670            } else {
4671                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4672            }
4673        }
4674    }
4675
4676    /**
4677     * Sets a delegate for implementing accessibility support via compositon as
4678     * opposed to inheritance. The delegate's primary use is for implementing
4679     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4680     *
4681     * @param delegate The delegate instance.
4682     *
4683     * @see AccessibilityDelegate
4684     */
4685    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4686        mAccessibilityDelegate = delegate;
4687    }
4688
4689    /**
4690     * Gets the provider for managing a virtual view hierarchy rooted at this View
4691     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4692     * that explore the window content.
4693     * <p>
4694     * If this method returns an instance, this instance is responsible for managing
4695     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4696     * View including the one representing the View itself. Similarly the returned
4697     * instance is responsible for performing accessibility actions on any virtual
4698     * view or the root view itself.
4699     * </p>
4700     * <p>
4701     * If an {@link AccessibilityDelegate} has been specified via calling
4702     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4703     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4704     * is responsible for handling this call.
4705     * </p>
4706     *
4707     * @return The provider.
4708     *
4709     * @see AccessibilityNodeProvider
4710     */
4711    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4712        if (mAccessibilityDelegate != null) {
4713            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4714        } else {
4715            return null;
4716        }
4717    }
4718
4719    /**
4720     * Gets the unique identifier of this view on the screen for accessibility purposes.
4721     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4722     *
4723     * @return The view accessibility id.
4724     *
4725     * @hide
4726     */
4727    public int getAccessibilityViewId() {
4728        if (mAccessibilityViewId == NO_ID) {
4729            mAccessibilityViewId = sNextAccessibilityViewId++;
4730        }
4731        return mAccessibilityViewId;
4732    }
4733
4734    /**
4735     * Gets the unique identifier of the window in which this View reseides.
4736     *
4737     * @return The window accessibility id.
4738     *
4739     * @hide
4740     */
4741    public int getAccessibilityWindowId() {
4742        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4743    }
4744
4745    /**
4746     * Gets the {@link View} description. It briefly describes the view and is
4747     * primarily used for accessibility support. Set this property to enable
4748     * better accessibility support for your application. This is especially
4749     * true for views that do not have textual representation (For example,
4750     * ImageButton).
4751     *
4752     * @return The content description.
4753     *
4754     * @attr ref android.R.styleable#View_contentDescription
4755     */
4756    @ViewDebug.ExportedProperty(category = "accessibility")
4757    public CharSequence getContentDescription() {
4758        return mContentDescription;
4759    }
4760
4761    /**
4762     * Sets the {@link View} description. It briefly describes the view and is
4763     * primarily used for accessibility support. Set this property to enable
4764     * better accessibility support for your application. This is especially
4765     * true for views that do not have textual representation (For example,
4766     * ImageButton).
4767     *
4768     * @param contentDescription The content description.
4769     *
4770     * @attr ref android.R.styleable#View_contentDescription
4771     */
4772    @RemotableViewMethod
4773    public void setContentDescription(CharSequence contentDescription) {
4774        mContentDescription = contentDescription;
4775    }
4776
4777    /**
4778     * Invoked whenever this view loses focus, either by losing window focus or by losing
4779     * focus within its window. This method can be used to clear any state tied to the
4780     * focus. For instance, if a button is held pressed with the trackball and the window
4781     * loses focus, this method can be used to cancel the press.
4782     *
4783     * Subclasses of View overriding this method should always call super.onFocusLost().
4784     *
4785     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4786     * @see #onWindowFocusChanged(boolean)
4787     *
4788     * @hide pending API council approval
4789     */
4790    protected void onFocusLost() {
4791        resetPressedState();
4792    }
4793
4794    private void resetPressedState() {
4795        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4796            return;
4797        }
4798
4799        if (isPressed()) {
4800            setPressed(false);
4801
4802            if (!mHasPerformedLongPress) {
4803                removeLongPressCallback();
4804            }
4805        }
4806    }
4807
4808    /**
4809     * Returns true if this view has focus
4810     *
4811     * @return True if this view has focus, false otherwise.
4812     */
4813    @ViewDebug.ExportedProperty(category = "focus")
4814    public boolean isFocused() {
4815        return (mPrivateFlags & FOCUSED) != 0;
4816    }
4817
4818    /**
4819     * Find the view in the hierarchy rooted at this view that currently has
4820     * focus.
4821     *
4822     * @return The view that currently has focus, or null if no focused view can
4823     *         be found.
4824     */
4825    public View findFocus() {
4826        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4827    }
4828
4829    /**
4830     * Indicates whether this view is one of the set of scrollable containers in
4831     * its window.
4832     *
4833     * @return whether this view is one of the set of scrollable containers in
4834     * its window
4835     *
4836     * @attr ref android.R.styleable#View_isScrollContainer
4837     */
4838    public boolean isScrollContainer() {
4839        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4840    }
4841
4842    /**
4843     * Change whether this view is one of the set of scrollable containers in
4844     * its window.  This will be used to determine whether the window can
4845     * resize or must pan when a soft input area is open -- scrollable
4846     * containers allow the window to use resize mode since the container
4847     * will appropriately shrink.
4848     *
4849     * @attr ref android.R.styleable#View_isScrollContainer
4850     */
4851    public void setScrollContainer(boolean isScrollContainer) {
4852        if (isScrollContainer) {
4853            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4854                mAttachInfo.mScrollContainers.add(this);
4855                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4856            }
4857            mPrivateFlags |= SCROLL_CONTAINER;
4858        } else {
4859            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4860                mAttachInfo.mScrollContainers.remove(this);
4861            }
4862            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4863        }
4864    }
4865
4866    /**
4867     * Returns the quality of the drawing cache.
4868     *
4869     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4870     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4871     *
4872     * @see #setDrawingCacheQuality(int)
4873     * @see #setDrawingCacheEnabled(boolean)
4874     * @see #isDrawingCacheEnabled()
4875     *
4876     * @attr ref android.R.styleable#View_drawingCacheQuality
4877     */
4878    public int getDrawingCacheQuality() {
4879        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4880    }
4881
4882    /**
4883     * Set the drawing cache quality of this view. This value is used only when the
4884     * drawing cache is enabled
4885     *
4886     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4887     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4888     *
4889     * @see #getDrawingCacheQuality()
4890     * @see #setDrawingCacheEnabled(boolean)
4891     * @see #isDrawingCacheEnabled()
4892     *
4893     * @attr ref android.R.styleable#View_drawingCacheQuality
4894     */
4895    public void setDrawingCacheQuality(int quality) {
4896        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4897    }
4898
4899    /**
4900     * Returns whether the screen should remain on, corresponding to the current
4901     * value of {@link #KEEP_SCREEN_ON}.
4902     *
4903     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4904     *
4905     * @see #setKeepScreenOn(boolean)
4906     *
4907     * @attr ref android.R.styleable#View_keepScreenOn
4908     */
4909    public boolean getKeepScreenOn() {
4910        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4911    }
4912
4913    /**
4914     * Controls whether the screen should remain on, modifying the
4915     * value of {@link #KEEP_SCREEN_ON}.
4916     *
4917     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4918     *
4919     * @see #getKeepScreenOn()
4920     *
4921     * @attr ref android.R.styleable#View_keepScreenOn
4922     */
4923    public void setKeepScreenOn(boolean keepScreenOn) {
4924        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4925    }
4926
4927    /**
4928     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4929     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4930     *
4931     * @attr ref android.R.styleable#View_nextFocusLeft
4932     */
4933    public int getNextFocusLeftId() {
4934        return mNextFocusLeftId;
4935    }
4936
4937    /**
4938     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4939     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4940     * decide automatically.
4941     *
4942     * @attr ref android.R.styleable#View_nextFocusLeft
4943     */
4944    public void setNextFocusLeftId(int nextFocusLeftId) {
4945        mNextFocusLeftId = nextFocusLeftId;
4946    }
4947
4948    /**
4949     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4950     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4951     *
4952     * @attr ref android.R.styleable#View_nextFocusRight
4953     */
4954    public int getNextFocusRightId() {
4955        return mNextFocusRightId;
4956    }
4957
4958    /**
4959     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4960     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4961     * decide automatically.
4962     *
4963     * @attr ref android.R.styleable#View_nextFocusRight
4964     */
4965    public void setNextFocusRightId(int nextFocusRightId) {
4966        mNextFocusRightId = nextFocusRightId;
4967    }
4968
4969    /**
4970     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4971     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4972     *
4973     * @attr ref android.R.styleable#View_nextFocusUp
4974     */
4975    public int getNextFocusUpId() {
4976        return mNextFocusUpId;
4977    }
4978
4979    /**
4980     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4981     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4982     * decide automatically.
4983     *
4984     * @attr ref android.R.styleable#View_nextFocusUp
4985     */
4986    public void setNextFocusUpId(int nextFocusUpId) {
4987        mNextFocusUpId = nextFocusUpId;
4988    }
4989
4990    /**
4991     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4992     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4993     *
4994     * @attr ref android.R.styleable#View_nextFocusDown
4995     */
4996    public int getNextFocusDownId() {
4997        return mNextFocusDownId;
4998    }
4999
5000    /**
5001     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5002     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5003     * decide automatically.
5004     *
5005     * @attr ref android.R.styleable#View_nextFocusDown
5006     */
5007    public void setNextFocusDownId(int nextFocusDownId) {
5008        mNextFocusDownId = nextFocusDownId;
5009    }
5010
5011    /**
5012     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5013     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5014     *
5015     * @attr ref android.R.styleable#View_nextFocusForward
5016     */
5017    public int getNextFocusForwardId() {
5018        return mNextFocusForwardId;
5019    }
5020
5021    /**
5022     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5023     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5024     * decide automatically.
5025     *
5026     * @attr ref android.R.styleable#View_nextFocusForward
5027     */
5028    public void setNextFocusForwardId(int nextFocusForwardId) {
5029        mNextFocusForwardId = nextFocusForwardId;
5030    }
5031
5032    /**
5033     * Returns the visibility of this view and all of its ancestors
5034     *
5035     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5036     */
5037    public boolean isShown() {
5038        View current = this;
5039        //noinspection ConstantConditions
5040        do {
5041            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5042                return false;
5043            }
5044            ViewParent parent = current.mParent;
5045            if (parent == null) {
5046                return false; // We are not attached to the view root
5047            }
5048            if (!(parent instanceof View)) {
5049                return true;
5050            }
5051            current = (View) parent;
5052        } while (current != null);
5053
5054        return false;
5055    }
5056
5057    /**
5058     * Called by the view hierarchy when the content insets for a window have
5059     * changed, to allow it to adjust its content to fit within those windows.
5060     * The content insets tell you the space that the status bar, input method,
5061     * and other system windows infringe on the application's window.
5062     *
5063     * <p>You do not normally need to deal with this function, since the default
5064     * window decoration given to applications takes care of applying it to the
5065     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5066     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5067     * and your content can be placed under those system elements.  You can then
5068     * use this method within your view hierarchy if you have parts of your UI
5069     * which you would like to ensure are not being covered.
5070     *
5071     * <p>The default implementation of this method simply applies the content
5072     * inset's to the view's padding.  This can be enabled through
5073     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5074     * the method and handle the insets however you would like.  Note that the
5075     * insets provided by the framework are always relative to the far edges
5076     * of the window, not accounting for the location of the called view within
5077     * that window.  (In fact when this method is called you do not yet know
5078     * where the layout will place the view, as it is done before layout happens.)
5079     *
5080     * <p>Note: unlike many View methods, there is no dispatch phase to this
5081     * call.  If you are overriding it in a ViewGroup and want to allow the
5082     * call to continue to your children, you must be sure to call the super
5083     * implementation.
5084     *
5085     * @param insets Current content insets of the window.  Prior to
5086     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5087     * the insets or else you and Android will be unhappy.
5088     *
5089     * @return Return true if this view applied the insets and it should not
5090     * continue propagating further down the hierarchy, false otherwise.
5091     */
5092    protected boolean fitSystemWindows(Rect insets) {
5093        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5094            mUserPaddingStart = -1;
5095            mUserPaddingEnd = -1;
5096            mUserPaddingRelative = false;
5097            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5098                    || mAttachInfo == null
5099                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5100                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5101                return true;
5102            } else {
5103                internalSetPadding(0, 0, 0, 0);
5104                return false;
5105            }
5106        }
5107        return false;
5108    }
5109
5110    /**
5111     * Set whether or not this view should account for system screen decorations
5112     * such as the status bar and inset its content. This allows this view to be
5113     * positioned in absolute screen coordinates and remain visible to the user.
5114     *
5115     * <p>This should only be used by top-level window decor views.
5116     *
5117     * @param fitSystemWindows true to inset content for system screen decorations, false for
5118     *                         default behavior.
5119     *
5120     * @attr ref android.R.styleable#View_fitsSystemWindows
5121     */
5122    public void setFitsSystemWindows(boolean fitSystemWindows) {
5123        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5124    }
5125
5126    /**
5127     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
5128     * will account for system screen decorations such as the status bar and inset its
5129     * content. This allows the view to be positioned in absolute screen coordinates
5130     * and remain visible to the user.
5131     *
5132     * @return true if this view will adjust its content bounds for system screen decorations.
5133     *
5134     * @attr ref android.R.styleable#View_fitsSystemWindows
5135     */
5136    public boolean fitsSystemWindows() {
5137        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5138    }
5139
5140    /**
5141     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5142     */
5143    public void requestFitSystemWindows() {
5144        if (mParent != null) {
5145            mParent.requestFitSystemWindows();
5146        }
5147    }
5148
5149    /**
5150     * For use by PhoneWindow to make its own system window fitting optional.
5151     * @hide
5152     */
5153    public void makeOptionalFitsSystemWindows() {
5154        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5155    }
5156
5157    /**
5158     * Returns the visibility status for this view.
5159     *
5160     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5161     * @attr ref android.R.styleable#View_visibility
5162     */
5163    @ViewDebug.ExportedProperty(mapping = {
5164        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5165        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5166        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5167    })
5168    public int getVisibility() {
5169        return mViewFlags & VISIBILITY_MASK;
5170    }
5171
5172    /**
5173     * Set the enabled state of this view.
5174     *
5175     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5176     * @attr ref android.R.styleable#View_visibility
5177     */
5178    @RemotableViewMethod
5179    public void setVisibility(int visibility) {
5180        setFlags(visibility, VISIBILITY_MASK);
5181        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5182    }
5183
5184    /**
5185     * Returns the enabled status for this view. The interpretation of the
5186     * enabled state varies by subclass.
5187     *
5188     * @return True if this view is enabled, false otherwise.
5189     */
5190    @ViewDebug.ExportedProperty
5191    public boolean isEnabled() {
5192        return (mViewFlags & ENABLED_MASK) == ENABLED;
5193    }
5194
5195    /**
5196     * Set the enabled state of this view. The interpretation of the enabled
5197     * state varies by subclass.
5198     *
5199     * @param enabled True if this view is enabled, false otherwise.
5200     */
5201    @RemotableViewMethod
5202    public void setEnabled(boolean enabled) {
5203        if (enabled == isEnabled()) return;
5204
5205        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5206
5207        /*
5208         * The View most likely has to change its appearance, so refresh
5209         * the drawable state.
5210         */
5211        refreshDrawableState();
5212
5213        // Invalidate too, since the default behavior for views is to be
5214        // be drawn at 50% alpha rather than to change the drawable.
5215        invalidate(true);
5216    }
5217
5218    /**
5219     * Set whether this view can receive the focus.
5220     *
5221     * Setting this to false will also ensure that this view is not focusable
5222     * in touch mode.
5223     *
5224     * @param focusable If true, this view can receive the focus.
5225     *
5226     * @see #setFocusableInTouchMode(boolean)
5227     * @attr ref android.R.styleable#View_focusable
5228     */
5229    public void setFocusable(boolean focusable) {
5230        if (!focusable) {
5231            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5232        }
5233        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5234    }
5235
5236    /**
5237     * Set whether this view can receive focus while in touch mode.
5238     *
5239     * Setting this to true will also ensure that this view is focusable.
5240     *
5241     * @param focusableInTouchMode If true, this view can receive the focus while
5242     *   in touch mode.
5243     *
5244     * @see #setFocusable(boolean)
5245     * @attr ref android.R.styleable#View_focusableInTouchMode
5246     */
5247    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5248        // Focusable in touch mode should always be set before the focusable flag
5249        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5250        // which, in touch mode, will not successfully request focus on this view
5251        // because the focusable in touch mode flag is not set
5252        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5253        if (focusableInTouchMode) {
5254            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5255        }
5256    }
5257
5258    /**
5259     * Set whether this view should have sound effects enabled for events such as
5260     * clicking and touching.
5261     *
5262     * <p>You may wish to disable sound effects for a view if you already play sounds,
5263     * for instance, a dial key that plays dtmf tones.
5264     *
5265     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5266     * @see #isSoundEffectsEnabled()
5267     * @see #playSoundEffect(int)
5268     * @attr ref android.R.styleable#View_soundEffectsEnabled
5269     */
5270    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5271        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5272    }
5273
5274    /**
5275     * @return whether this view should have sound effects enabled for events such as
5276     *     clicking and touching.
5277     *
5278     * @see #setSoundEffectsEnabled(boolean)
5279     * @see #playSoundEffect(int)
5280     * @attr ref android.R.styleable#View_soundEffectsEnabled
5281     */
5282    @ViewDebug.ExportedProperty
5283    public boolean isSoundEffectsEnabled() {
5284        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5285    }
5286
5287    /**
5288     * Set whether this view should have haptic feedback for events such as
5289     * long presses.
5290     *
5291     * <p>You may wish to disable haptic feedback if your view already controls
5292     * its own haptic feedback.
5293     *
5294     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5295     * @see #isHapticFeedbackEnabled()
5296     * @see #performHapticFeedback(int)
5297     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5298     */
5299    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5300        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5301    }
5302
5303    /**
5304     * @return whether this view should have haptic feedback enabled for events
5305     * long presses.
5306     *
5307     * @see #setHapticFeedbackEnabled(boolean)
5308     * @see #performHapticFeedback(int)
5309     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5310     */
5311    @ViewDebug.ExportedProperty
5312    public boolean isHapticFeedbackEnabled() {
5313        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5314    }
5315
5316    /**
5317     * Returns the layout direction for this view.
5318     *
5319     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5320     *   {@link #LAYOUT_DIRECTION_RTL},
5321     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5322     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5323     * @attr ref android.R.styleable#View_layoutDirection
5324     */
5325    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5326        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5327        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5328        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5329        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5330    })
5331    public int getLayoutDirection() {
5332        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5333    }
5334
5335    /**
5336     * Set the layout direction for this view. This will propagate a reset of layout direction
5337     * resolution to the view's children and resolve layout direction for this view.
5338     *
5339     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5340     *   {@link #LAYOUT_DIRECTION_RTL},
5341     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5342     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5343     *
5344     * @attr ref android.R.styleable#View_layoutDirection
5345     */
5346    @RemotableViewMethod
5347    public void setLayoutDirection(int layoutDirection) {
5348        if (getLayoutDirection() != layoutDirection) {
5349            // Reset the current layout direction and the resolved one
5350            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5351            resetResolvedLayoutDirection();
5352            // Set the new layout direction (filtered) and ask for a layout pass
5353            mPrivateFlags2 |=
5354                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5355            requestLayout();
5356        }
5357    }
5358
5359    /**
5360     * Returns the resolved layout direction for this view.
5361     *
5362     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5363     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5364     */
5365    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5366        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5367        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5368    })
5369    public int getResolvedLayoutDirection() {
5370        // The layout diretion will be resolved only if needed
5371        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5372            resolveLayoutDirection();
5373        }
5374        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5375                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5376    }
5377
5378    /**
5379     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5380     * layout attribute and/or the inherited value from the parent
5381     *
5382     * @return true if the layout is right-to-left.
5383     */
5384    @ViewDebug.ExportedProperty(category = "layout")
5385    public boolean isLayoutRtl() {
5386        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5387    }
5388
5389    /**
5390     * Indicates whether the view is currently tracking transient state that the
5391     * app should not need to concern itself with saving and restoring, but that
5392     * the framework should take special note to preserve when possible.
5393     *
5394     * @return true if the view has transient state
5395     */
5396    @ViewDebug.ExportedProperty(category = "layout")
5397    public boolean hasTransientState() {
5398        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5399    }
5400
5401    /**
5402     * Set whether this view is currently tracking transient state that the
5403     * framework should attempt to preserve when possible.
5404     *
5405     * @param hasTransientState true if this view has transient state
5406     */
5407    public void setHasTransientState(boolean hasTransientState) {
5408        if (hasTransientState() == hasTransientState) return;
5409
5410        mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5411                (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5412        if (mParent != null) {
5413            try {
5414                mParent.childHasTransientStateChanged(this, hasTransientState);
5415            } catch (AbstractMethodError e) {
5416                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5417                        " does not fully implement ViewParent", e);
5418            }
5419        }
5420    }
5421
5422    /**
5423     * If this view doesn't do any drawing on its own, set this flag to
5424     * allow further optimizations. By default, this flag is not set on
5425     * View, but could be set on some View subclasses such as ViewGroup.
5426     *
5427     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5428     * you should clear this flag.
5429     *
5430     * @param willNotDraw whether or not this View draw on its own
5431     */
5432    public void setWillNotDraw(boolean willNotDraw) {
5433        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5434    }
5435
5436    /**
5437     * Returns whether or not this View draws on its own.
5438     *
5439     * @return true if this view has nothing to draw, false otherwise
5440     */
5441    @ViewDebug.ExportedProperty(category = "drawing")
5442    public boolean willNotDraw() {
5443        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5444    }
5445
5446    /**
5447     * When a View's drawing cache is enabled, drawing is redirected to an
5448     * offscreen bitmap. Some views, like an ImageView, must be able to
5449     * bypass this mechanism if they already draw a single bitmap, to avoid
5450     * unnecessary usage of the memory.
5451     *
5452     * @param willNotCacheDrawing true if this view does not cache its
5453     *        drawing, false otherwise
5454     */
5455    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5456        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5457    }
5458
5459    /**
5460     * Returns whether or not this View can cache its drawing or not.
5461     *
5462     * @return true if this view does not cache its drawing, false otherwise
5463     */
5464    @ViewDebug.ExportedProperty(category = "drawing")
5465    public boolean willNotCacheDrawing() {
5466        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5467    }
5468
5469    /**
5470     * Indicates whether this view reacts to click events or not.
5471     *
5472     * @return true if the view is clickable, false otherwise
5473     *
5474     * @see #setClickable(boolean)
5475     * @attr ref android.R.styleable#View_clickable
5476     */
5477    @ViewDebug.ExportedProperty
5478    public boolean isClickable() {
5479        return (mViewFlags & CLICKABLE) == CLICKABLE;
5480    }
5481
5482    /**
5483     * Enables or disables click events for this view. When a view
5484     * is clickable it will change its state to "pressed" on every click.
5485     * Subclasses should set the view clickable to visually react to
5486     * user's clicks.
5487     *
5488     * @param clickable true to make the view clickable, false otherwise
5489     *
5490     * @see #isClickable()
5491     * @attr ref android.R.styleable#View_clickable
5492     */
5493    public void setClickable(boolean clickable) {
5494        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5495    }
5496
5497    /**
5498     * Indicates whether this view reacts to long click events or not.
5499     *
5500     * @return true if the view is long clickable, false otherwise
5501     *
5502     * @see #setLongClickable(boolean)
5503     * @attr ref android.R.styleable#View_longClickable
5504     */
5505    public boolean isLongClickable() {
5506        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5507    }
5508
5509    /**
5510     * Enables or disables long click events for this view. When a view is long
5511     * clickable it reacts to the user holding down the button for a longer
5512     * duration than a tap. This event can either launch the listener or a
5513     * context menu.
5514     *
5515     * @param longClickable true to make the view long clickable, false otherwise
5516     * @see #isLongClickable()
5517     * @attr ref android.R.styleable#View_longClickable
5518     */
5519    public void setLongClickable(boolean longClickable) {
5520        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5521    }
5522
5523    /**
5524     * Sets the pressed state for this view.
5525     *
5526     * @see #isClickable()
5527     * @see #setClickable(boolean)
5528     *
5529     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5530     *        the View's internal state from a previously set "pressed" state.
5531     */
5532    public void setPressed(boolean pressed) {
5533        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5534
5535        if (pressed) {
5536            mPrivateFlags |= PRESSED;
5537        } else {
5538            mPrivateFlags &= ~PRESSED;
5539        }
5540
5541        if (needsRefresh) {
5542            refreshDrawableState();
5543        }
5544        dispatchSetPressed(pressed);
5545    }
5546
5547    /**
5548     * Dispatch setPressed to all of this View's children.
5549     *
5550     * @see #setPressed(boolean)
5551     *
5552     * @param pressed The new pressed state
5553     */
5554    protected void dispatchSetPressed(boolean pressed) {
5555    }
5556
5557    /**
5558     * Indicates whether the view is currently in pressed state. Unless
5559     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5560     * the pressed state.
5561     *
5562     * @see #setPressed(boolean)
5563     * @see #isClickable()
5564     * @see #setClickable(boolean)
5565     *
5566     * @return true if the view is currently pressed, false otherwise
5567     */
5568    public boolean isPressed() {
5569        return (mPrivateFlags & PRESSED) == PRESSED;
5570    }
5571
5572    /**
5573     * Indicates whether this view will save its state (that is,
5574     * whether its {@link #onSaveInstanceState} method will be called).
5575     *
5576     * @return Returns true if the view state saving is enabled, else false.
5577     *
5578     * @see #setSaveEnabled(boolean)
5579     * @attr ref android.R.styleable#View_saveEnabled
5580     */
5581    public boolean isSaveEnabled() {
5582        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5583    }
5584
5585    /**
5586     * Controls whether the saving of this view's state is
5587     * enabled (that is, whether its {@link #onSaveInstanceState} method
5588     * will be called).  Note that even if freezing is enabled, the
5589     * view still must have an id assigned to it (via {@link #setId(int)})
5590     * for its state to be saved.  This flag can only disable the
5591     * saving of this view; any child views may still have their state saved.
5592     *
5593     * @param enabled Set to false to <em>disable</em> state saving, or true
5594     * (the default) to allow it.
5595     *
5596     * @see #isSaveEnabled()
5597     * @see #setId(int)
5598     * @see #onSaveInstanceState()
5599     * @attr ref android.R.styleable#View_saveEnabled
5600     */
5601    public void setSaveEnabled(boolean enabled) {
5602        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5603    }
5604
5605    /**
5606     * Gets whether the framework should discard touches when the view's
5607     * window is obscured by another visible window.
5608     * Refer to the {@link View} security documentation for more details.
5609     *
5610     * @return True if touch filtering is enabled.
5611     *
5612     * @see #setFilterTouchesWhenObscured(boolean)
5613     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5614     */
5615    @ViewDebug.ExportedProperty
5616    public boolean getFilterTouchesWhenObscured() {
5617        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5618    }
5619
5620    /**
5621     * Sets whether the framework should discard touches when the view's
5622     * window is obscured by another visible window.
5623     * Refer to the {@link View} security documentation for more details.
5624     *
5625     * @param enabled True if touch filtering should be enabled.
5626     *
5627     * @see #getFilterTouchesWhenObscured
5628     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5629     */
5630    public void setFilterTouchesWhenObscured(boolean enabled) {
5631        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5632                FILTER_TOUCHES_WHEN_OBSCURED);
5633    }
5634
5635    /**
5636     * Indicates whether the entire hierarchy under this view will save its
5637     * state when a state saving traversal occurs from its parent.  The default
5638     * is true; if false, these views will not be saved unless
5639     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5640     *
5641     * @return Returns true if the view state saving from parent is enabled, else false.
5642     *
5643     * @see #setSaveFromParentEnabled(boolean)
5644     */
5645    public boolean isSaveFromParentEnabled() {
5646        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5647    }
5648
5649    /**
5650     * Controls whether the entire hierarchy under this view will save its
5651     * state when a state saving traversal occurs from its parent.  The default
5652     * is true; if false, these views will not be saved unless
5653     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5654     *
5655     * @param enabled Set to false to <em>disable</em> state saving, or true
5656     * (the default) to allow it.
5657     *
5658     * @see #isSaveFromParentEnabled()
5659     * @see #setId(int)
5660     * @see #onSaveInstanceState()
5661     */
5662    public void setSaveFromParentEnabled(boolean enabled) {
5663        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5664    }
5665
5666
5667    /**
5668     * Returns whether this View is able to take focus.
5669     *
5670     * @return True if this view can take focus, or false otherwise.
5671     * @attr ref android.R.styleable#View_focusable
5672     */
5673    @ViewDebug.ExportedProperty(category = "focus")
5674    public final boolean isFocusable() {
5675        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5676    }
5677
5678    /**
5679     * When a view is focusable, it may not want to take focus when in touch mode.
5680     * For example, a button would like focus when the user is navigating via a D-pad
5681     * so that the user can click on it, but once the user starts touching the screen,
5682     * the button shouldn't take focus
5683     * @return Whether the view is focusable in touch mode.
5684     * @attr ref android.R.styleable#View_focusableInTouchMode
5685     */
5686    @ViewDebug.ExportedProperty
5687    public final boolean isFocusableInTouchMode() {
5688        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5689    }
5690
5691    /**
5692     * Find the nearest view in the specified direction that can take focus.
5693     * This does not actually give focus to that view.
5694     *
5695     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5696     *
5697     * @return The nearest focusable in the specified direction, or null if none
5698     *         can be found.
5699     */
5700    public View focusSearch(int direction) {
5701        if (mParent != null) {
5702            return mParent.focusSearch(this, direction);
5703        } else {
5704            return null;
5705        }
5706    }
5707
5708    /**
5709     * This method is the last chance for the focused view and its ancestors to
5710     * respond to an arrow key. This is called when the focused view did not
5711     * consume the key internally, nor could the view system find a new view in
5712     * the requested direction to give focus to.
5713     *
5714     * @param focused The currently focused view.
5715     * @param direction The direction focus wants to move. One of FOCUS_UP,
5716     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5717     * @return True if the this view consumed this unhandled move.
5718     */
5719    public boolean dispatchUnhandledMove(View focused, int direction) {
5720        return false;
5721    }
5722
5723    /**
5724     * If a user manually specified the next view id for a particular direction,
5725     * use the root to look up the view.
5726     * @param root The root view of the hierarchy containing this view.
5727     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5728     * or FOCUS_BACKWARD.
5729     * @return The user specified next view, or null if there is none.
5730     */
5731    View findUserSetNextFocus(View root, int direction) {
5732        switch (direction) {
5733            case FOCUS_LEFT:
5734                if (mNextFocusLeftId == View.NO_ID) return null;
5735                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5736            case FOCUS_RIGHT:
5737                if (mNextFocusRightId == View.NO_ID) return null;
5738                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5739            case FOCUS_UP:
5740                if (mNextFocusUpId == View.NO_ID) return null;
5741                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5742            case FOCUS_DOWN:
5743                if (mNextFocusDownId == View.NO_ID) return null;
5744                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5745            case FOCUS_FORWARD:
5746                if (mNextFocusForwardId == View.NO_ID) return null;
5747                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5748            case FOCUS_BACKWARD: {
5749                if (mID == View.NO_ID) return null;
5750                final int id = mID;
5751                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5752                    @Override
5753                    public boolean apply(View t) {
5754                        return t.mNextFocusForwardId == id;
5755                    }
5756                });
5757            }
5758        }
5759        return null;
5760    }
5761
5762    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5763        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5764            @Override
5765            public boolean apply(View t) {
5766                return t.mID == childViewId;
5767            }
5768        });
5769
5770        if (result == null) {
5771            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5772                    + "by user for id " + childViewId);
5773        }
5774        return result;
5775    }
5776
5777    /**
5778     * Find and return all focusable views that are descendants of this view,
5779     * possibly including this view if it is focusable itself.
5780     *
5781     * @param direction The direction of the focus
5782     * @return A list of focusable views
5783     */
5784    public ArrayList<View> getFocusables(int direction) {
5785        ArrayList<View> result = new ArrayList<View>(24);
5786        addFocusables(result, direction);
5787        return result;
5788    }
5789
5790    /**
5791     * Add any focusable views that are descendants of this view (possibly
5792     * including this view if it is focusable itself) to views.  If we are in touch mode,
5793     * only add views that are also focusable in touch mode.
5794     *
5795     * @param views Focusable views found so far
5796     * @param direction The direction of the focus
5797     */
5798    public void addFocusables(ArrayList<View> views, int direction) {
5799        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5800    }
5801
5802    /**
5803     * Adds any focusable views that are descendants of this view (possibly
5804     * including this view if it is focusable itself) to views. This method
5805     * adds all focusable views regardless if we are in touch mode or
5806     * only views focusable in touch mode if we are in touch mode or
5807     * only views that can take accessibility focus if accessibility is enabeld
5808     * depending on the focusable mode paramater.
5809     *
5810     * @param views Focusable views found so far or null if all we are interested is
5811     *        the number of focusables.
5812     * @param direction The direction of the focus.
5813     * @param focusableMode The type of focusables to be added.
5814     *
5815     * @see #FOCUSABLES_ALL
5816     * @see #FOCUSABLES_TOUCH_MODE
5817     */
5818    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5819        if (views == null) {
5820            return;
5821        }
5822        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
5823            if (AccessibilityManager.getInstance(mContext).isEnabled()
5824                    && includeForAccessibility()) {
5825                views.add(this);
5826                return;
5827            }
5828        }
5829        if (!isFocusable()) {
5830            return;
5831        }
5832        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
5833                && isInTouchMode() && !isFocusableInTouchMode()) {
5834            return;
5835        }
5836        views.add(this);
5837    }
5838
5839    /**
5840     * Finds the Views that contain given text. The containment is case insensitive.
5841     * The search is performed by either the text that the View renders or the content
5842     * description that describes the view for accessibility purposes and the view does
5843     * not render or both. Clients can specify how the search is to be performed via
5844     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5845     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5846     *
5847     * @param outViews The output list of matching Views.
5848     * @param searched The text to match against.
5849     *
5850     * @see #FIND_VIEWS_WITH_TEXT
5851     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5852     * @see #setContentDescription(CharSequence)
5853     */
5854    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5855        if (getAccessibilityNodeProvider() != null) {
5856            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5857                outViews.add(this);
5858            }
5859        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5860                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5861            String searchedLowerCase = searched.toString().toLowerCase();
5862            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5863            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5864                outViews.add(this);
5865            }
5866        }
5867    }
5868
5869    /**
5870     * Find and return all touchable views that are descendants of this view,
5871     * possibly including this view if it is touchable itself.
5872     *
5873     * @return A list of touchable views
5874     */
5875    public ArrayList<View> getTouchables() {
5876        ArrayList<View> result = new ArrayList<View>();
5877        addTouchables(result);
5878        return result;
5879    }
5880
5881    /**
5882     * Add any touchable views that are descendants of this view (possibly
5883     * including this view if it is touchable itself) to views.
5884     *
5885     * @param views Touchable views found so far
5886     */
5887    public void addTouchables(ArrayList<View> views) {
5888        final int viewFlags = mViewFlags;
5889
5890        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5891                && (viewFlags & ENABLED_MASK) == ENABLED) {
5892            views.add(this);
5893        }
5894    }
5895
5896    /**
5897     * Returns whether this View is accessibility focused.
5898     *
5899     * @return True if this View is accessibility focused.
5900     */
5901    boolean isAccessibilityFocused() {
5902        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
5903    }
5904
5905    /**
5906     * Call this to try to give accessibility focus to this view.
5907     *
5908     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
5909     * returns false or the view is no visible or the view already has accessibility
5910     * focus.
5911     *
5912     * See also {@link #focusSearch(int)}, which is what you call to say that you
5913     * have focus, and you want your parent to look for the next one.
5914     *
5915     * @return Whether this view actually took accessibility focus.
5916     *
5917     * @hide
5918     */
5919    public boolean requestAccessibilityFocus() {
5920        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
5921            return false;
5922        }
5923        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5924            return false;
5925        }
5926        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
5927            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
5928            ViewRootImpl viewRootImpl = getViewRootImpl();
5929            if (viewRootImpl != null) {
5930                viewRootImpl.setAccessibilityFocusedHost(this);
5931            }
5932            invalidate();
5933            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
5934            notifyAccessibilityStateChanged();
5935            // Try to give input focus to this view - not a descendant.
5936            requestFocusNoSearch(View.FOCUS_DOWN, null);
5937            return true;
5938        }
5939        return false;
5940    }
5941
5942    /**
5943     * Call this to try to clear accessibility focus of this view.
5944     *
5945     * See also {@link #focusSearch(int)}, which is what you call to say that you
5946     * have focus, and you want your parent to look for the next one.
5947     *
5948     * @hide
5949     */
5950    public void clearAccessibilityFocus() {
5951        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
5952            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
5953            ViewRootImpl viewRootImpl = getViewRootImpl();
5954            if (viewRootImpl != null) {
5955                viewRootImpl.setAccessibilityFocusedHost(null);
5956            }
5957            invalidate();
5958            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
5959            notifyAccessibilityStateChanged();
5960            // Try to move accessibility focus to the input focus.
5961            View rootView = getRootView();
5962            if (rootView != null) {
5963                View inputFocus = rootView.findFocus();
5964                if (inputFocus != null) {
5965                    inputFocus.requestAccessibilityFocus();
5966                }
5967            }
5968        }
5969    }
5970
5971    /**
5972     * Find the best view to take accessibility focus from a hover.
5973     * This function finds the deepest actionable view and if that
5974     * fails ask the parent to take accessibility focus from hover.
5975     *
5976     * @param x The X hovered location in this view coorditantes.
5977     * @param y The Y hovered location in this view coorditantes.
5978     * @return Whether the request was handled.
5979     *
5980     * @hide
5981     */
5982    public boolean requestAccessibilityFocusFromHover(float x, float y) {
5983        if (onRequestAccessibilityFocusFromHover(x, y)) {
5984            return true;
5985        }
5986        ViewParent parent = mParent;
5987        if (parent instanceof View) {
5988            View parentView = (View) parent;
5989
5990            float[] position = mAttachInfo.mTmpTransformLocation;
5991            position[0] = x;
5992            position[1] = y;
5993
5994            // Compensate for the transformation of the current matrix.
5995            if (!hasIdentityMatrix()) {
5996                getMatrix().mapPoints(position);
5997            }
5998
5999            // Compensate for the parent scroll and the offset
6000            // of this view stop from the parent top.
6001            position[0] += mLeft - parentView.mScrollX;
6002            position[1] += mTop - parentView.mScrollY;
6003
6004            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6005        }
6006        return false;
6007    }
6008
6009    /**
6010     * Requests to give this View focus from hover.
6011     *
6012     * @param x The X hovered location in this view coorditantes.
6013     * @param y The Y hovered location in this view coorditantes.
6014     * @return Whether the request was handled.
6015     *
6016     * @hide
6017     */
6018    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6019        if (includeForAccessibility()
6020                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6021            return requestAccessibilityFocus();
6022        }
6023        return false;
6024    }
6025
6026    /**
6027     * Clears accessibility focus without calling any callback methods
6028     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6029     * is used for clearing accessibility focus when giving this focus to
6030     * another view.
6031     */
6032    void clearAccessibilityFocusNoCallbacks() {
6033        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6034            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6035            invalidate();
6036        }
6037    }
6038
6039    /**
6040     * Call this to try to give focus to a specific view or to one of its
6041     * descendants.
6042     *
6043     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6044     * false), or if it is focusable and it is not focusable in touch mode
6045     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6046     *
6047     * See also {@link #focusSearch(int)}, which is what you call to say that you
6048     * have focus, and you want your parent to look for the next one.
6049     *
6050     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6051     * {@link #FOCUS_DOWN} and <code>null</code>.
6052     *
6053     * @return Whether this view or one of its descendants actually took focus.
6054     */
6055    public final boolean requestFocus() {
6056        return requestFocus(View.FOCUS_DOWN);
6057    }
6058
6059    /**
6060     * Call this to try to give focus to a specific view or to one of its
6061     * descendants and give it a hint about what direction focus is heading.
6062     *
6063     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6064     * false), or if it is focusable and it is not focusable in touch mode
6065     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6066     *
6067     * See also {@link #focusSearch(int)}, which is what you call to say that you
6068     * have focus, and you want your parent to look for the next one.
6069     *
6070     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6071     * <code>null</code> set for the previously focused rectangle.
6072     *
6073     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6074     * @return Whether this view or one of its descendants actually took focus.
6075     */
6076    public final boolean requestFocus(int direction) {
6077        return requestFocus(direction, null);
6078    }
6079
6080    /**
6081     * Call this to try to give focus to a specific view or to one of its descendants
6082     * and give it hints about the direction and a specific rectangle that the focus
6083     * is coming from.  The rectangle can help give larger views a finer grained hint
6084     * about where focus is coming from, and therefore, where to show selection, or
6085     * forward focus change internally.
6086     *
6087     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6088     * false), or if it is focusable and it is not focusable in touch mode
6089     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6090     *
6091     * A View will not take focus if it is not visible.
6092     *
6093     * A View will not take focus if one of its parents has
6094     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6095     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6096     *
6097     * See also {@link #focusSearch(int)}, which is what you call to say that you
6098     * have focus, and you want your parent to look for the next one.
6099     *
6100     * You may wish to override this method if your custom {@link View} has an internal
6101     * {@link View} that it wishes to forward the request to.
6102     *
6103     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6104     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6105     *        to give a finer grained hint about where focus is coming from.  May be null
6106     *        if there is no hint.
6107     * @return Whether this view or one of its descendants actually took focus.
6108     */
6109    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6110        return requestFocusNoSearch(direction, previouslyFocusedRect);
6111    }
6112
6113    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6114        // need to be focusable
6115        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6116                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6117            return false;
6118        }
6119
6120        // need to be focusable in touch mode if in touch mode
6121        if (isInTouchMode() &&
6122            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6123               return false;
6124        }
6125
6126        // need to not have any parents blocking us
6127        if (hasAncestorThatBlocksDescendantFocus()) {
6128            return false;
6129        }
6130
6131        handleFocusGainInternal(direction, previouslyFocusedRect);
6132        return true;
6133    }
6134
6135    /**
6136     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6137     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6138     * touch mode to request focus when they are touched.
6139     *
6140     * @return Whether this view or one of its descendants actually took focus.
6141     *
6142     * @see #isInTouchMode()
6143     *
6144     */
6145    public final boolean requestFocusFromTouch() {
6146        // Leave touch mode if we need to
6147        if (isInTouchMode()) {
6148            ViewRootImpl viewRoot = getViewRootImpl();
6149            if (viewRoot != null) {
6150                viewRoot.ensureTouchMode(false);
6151            }
6152        }
6153        return requestFocus(View.FOCUS_DOWN);
6154    }
6155
6156    /**
6157     * @return Whether any ancestor of this view blocks descendant focus.
6158     */
6159    private boolean hasAncestorThatBlocksDescendantFocus() {
6160        ViewParent ancestor = mParent;
6161        while (ancestor instanceof ViewGroup) {
6162            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6163            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6164                return true;
6165            } else {
6166                ancestor = vgAncestor.getParent();
6167            }
6168        }
6169        return false;
6170    }
6171
6172    /**
6173     * Gets the mode for determining whether this View is important for accessibility
6174     * which is if it fires accessibility events and if it is reported to
6175     * accessibility services that query the screen.
6176     *
6177     * @return The mode for determining whether a View is important for accessibility.
6178     *
6179     * @attr ref android.R.styleable#View_importantForAccessibility
6180     *
6181     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6182     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6183     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6184     */
6185    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6186            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6187                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6188            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6189                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6190            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6191                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6192        })
6193    public int getImportantForAccessibility() {
6194        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6195                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6196    }
6197
6198    /**
6199     * Sets how to determine whether this view is important for accessibility
6200     * which is if it fires accessibility events and if it is reported to
6201     * accessibility services that query the screen.
6202     *
6203     * @param mode How to determine whether this view is important for accessibility.
6204     *
6205     * @attr ref android.R.styleable#View_importantForAccessibility
6206     *
6207     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6208     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6209     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6210     */
6211    public void setImportantForAccessibility(int mode) {
6212        if (mode != getImportantForAccessibility()) {
6213            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6214            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6215                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6216            notifyAccessibilityStateChanged();
6217        }
6218    }
6219
6220    /**
6221     * Gets whether this view should be exposed for accessibility.
6222     *
6223     * @return Whether the view is exposed for accessibility.
6224     *
6225     * @hide
6226     */
6227    public boolean isImportantForAccessibility() {
6228        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6229                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6230        switch (mode) {
6231            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6232                return true;
6233            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6234                return false;
6235            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6236                return isActionableForAccessibility() || hasListenersForAccessibility();
6237            default:
6238                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6239                        + mode);
6240        }
6241    }
6242
6243    /**
6244     * Gets the parent for accessibility purposes. Note that the parent for
6245     * accessibility is not necessary the immediate parent. It is the first
6246     * predecessor that is important for accessibility.
6247     *
6248     * @return The parent for accessibility purposes.
6249     */
6250    public ViewParent getParentForAccessibility() {
6251        if (mParent instanceof View) {
6252            View parentView = (View) mParent;
6253            if (parentView.includeForAccessibility()) {
6254                return mParent;
6255            } else {
6256                return mParent.getParentForAccessibility();
6257            }
6258        }
6259        return null;
6260    }
6261
6262    /**
6263     * Adds the children of a given View for accessibility. Since some Views are
6264     * not important for accessibility the children for accessibility are not
6265     * necessarily direct children of the riew, rather they are the first level of
6266     * descendants important for accessibility.
6267     *
6268     * @param children The list of children for accessibility.
6269     */
6270    public void addChildrenForAccessibility(ArrayList<View> children) {
6271        if (includeForAccessibility()) {
6272            children.add(this);
6273        }
6274    }
6275
6276    /**
6277     * Whether to regard this view for accessibility. A view is regarded for
6278     * accessibility if it is important for accessibility or the querying
6279     * accessibility service has explicitly requested that view not
6280     * important for accessibility are regarded.
6281     *
6282     * @return Whether to regard the view for accessibility.
6283     */
6284    boolean includeForAccessibility() {
6285        if (mAttachInfo != null) {
6286            if (!mAttachInfo.mIncludeNotImportantViews) {
6287                return isImportantForAccessibility();
6288            } else {
6289                return true;
6290            }
6291        }
6292        return false;
6293    }
6294
6295    /**
6296     * Returns whether the View is considered actionable from
6297     * accessibility perspective. Such view are important for
6298     * accessiiblity.
6299     *
6300     * @return True if the view is actionable for accessibility.
6301     */
6302    private boolean isActionableForAccessibility() {
6303        return (isClickable() || isLongClickable() || isFocusable());
6304    }
6305
6306    /**
6307     * Returns whether the View has registered callbacks wich makes it
6308     * important for accessiiblity.
6309     *
6310     * @return True if the view is actionable for accessibility.
6311     */
6312    private boolean hasListenersForAccessibility() {
6313        ListenerInfo info = getListenerInfo();
6314        return mTouchDelegate != null || info.mOnKeyListener != null
6315                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6316                || info.mOnHoverListener != null || info.mOnDragListener != null;
6317    }
6318
6319    /**
6320     * Notifies accessibility services that some view's important for
6321     * accessibility state has changed. Note that such notifications
6322     * are made at most once every
6323     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6324     * to avoid unnecessary load to the system. Also once a view has
6325     * made a notifucation this method is a NOP until the notification has
6326     * been sent to clients.
6327     *
6328     * @hide
6329     *
6330     * TODO: Makse sure this method is called for any view state change
6331     *       that is interesting for accessilility purposes.
6332     */
6333    public void notifyAccessibilityStateChanged() {
6334        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6335            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6336            if (mParent != null) {
6337                mParent.childAccessibilityStateChanged(this);
6338            }
6339        }
6340    }
6341
6342    /**
6343     * Reset the state indicating the this view has requested clients
6344     * interested in its accessiblity state to be notified.
6345     *
6346     * @hide
6347     */
6348    public void resetAccessibilityStateChanged() {
6349        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6350    }
6351
6352    /**
6353     * Performs the specified accessibility action on the view. For
6354     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6355     *
6356     * @param action The action to perform.
6357     * @return Whether the action was performed.
6358     */
6359    public boolean performAccessibilityAction(int action) {
6360        switch (action) {
6361            case AccessibilityNodeInfo.ACTION_CLICK: {
6362                if (isClickable()) {
6363                    performClick();
6364                }
6365            } break;
6366            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6367                if (isLongClickable()) {
6368                    performLongClick();
6369                }
6370            } break;
6371            case AccessibilityNodeInfo.ACTION_FOCUS: {
6372                if (!hasFocus()) {
6373                    // Get out of touch mode since accessibility
6374                    // wants to move focus around.
6375                    getViewRootImpl().ensureTouchMode(false);
6376                    return requestFocus();
6377                }
6378            } break;
6379            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6380                if (hasFocus()) {
6381                    clearFocus();
6382                    return !isFocused();
6383                }
6384            } break;
6385            case AccessibilityNodeInfo.ACTION_SELECT: {
6386                if (!isSelected()) {
6387                    setSelected(true);
6388                    return isSelected();
6389                }
6390            } break;
6391            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6392                if (isSelected()) {
6393                    setSelected(false);
6394                    return !isSelected();
6395                }
6396            } break;
6397            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6398                if (!isAccessibilityFocused()) {
6399                    return requestAccessibilityFocus();
6400                }
6401            } break;
6402            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6403                if (isAccessibilityFocused()) {
6404                    clearAccessibilityFocus();
6405                    return true;
6406                }
6407            } break;
6408        }
6409        return false;
6410    }
6411
6412    /**
6413     * @hide
6414     */
6415    public void dispatchStartTemporaryDetach() {
6416        onStartTemporaryDetach();
6417    }
6418
6419    /**
6420     * This is called when a container is going to temporarily detach a child, with
6421     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6422     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6423     * {@link #onDetachedFromWindow()} when the container is done.
6424     */
6425    public void onStartTemporaryDetach() {
6426        removeUnsetPressCallback();
6427        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6428    }
6429
6430    /**
6431     * @hide
6432     */
6433    public void dispatchFinishTemporaryDetach() {
6434        onFinishTemporaryDetach();
6435    }
6436
6437    /**
6438     * Called after {@link #onStartTemporaryDetach} when the container is done
6439     * changing the view.
6440     */
6441    public void onFinishTemporaryDetach() {
6442    }
6443
6444    /**
6445     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6446     * for this view's window.  Returns null if the view is not currently attached
6447     * to the window.  Normally you will not need to use this directly, but
6448     * just use the standard high-level event callbacks like
6449     * {@link #onKeyDown(int, KeyEvent)}.
6450     */
6451    public KeyEvent.DispatcherState getKeyDispatcherState() {
6452        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6453    }
6454
6455    /**
6456     * Dispatch a key event before it is processed by any input method
6457     * associated with the view hierarchy.  This can be used to intercept
6458     * key events in special situations before the IME consumes them; a
6459     * typical example would be handling the BACK key to update the application's
6460     * UI instead of allowing the IME to see it and close itself.
6461     *
6462     * @param event The key event to be dispatched.
6463     * @return True if the event was handled, false otherwise.
6464     */
6465    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6466        return onKeyPreIme(event.getKeyCode(), event);
6467    }
6468
6469    /**
6470     * Dispatch a key event to the next view on the focus path. This path runs
6471     * from the top of the view tree down to the currently focused view. If this
6472     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6473     * the next node down the focus path. This method also fires any key
6474     * listeners.
6475     *
6476     * @param event The key event to be dispatched.
6477     * @return True if the event was handled, false otherwise.
6478     */
6479    public boolean dispatchKeyEvent(KeyEvent event) {
6480        if (mInputEventConsistencyVerifier != null) {
6481            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6482        }
6483
6484        // Give any attached key listener a first crack at the event.
6485        //noinspection SimplifiableIfStatement
6486        ListenerInfo li = mListenerInfo;
6487        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6488                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6489            return true;
6490        }
6491
6492        if (event.dispatch(this, mAttachInfo != null
6493                ? mAttachInfo.mKeyDispatchState : null, this)) {
6494            return true;
6495        }
6496
6497        if (mInputEventConsistencyVerifier != null) {
6498            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6499        }
6500        return false;
6501    }
6502
6503    /**
6504     * Dispatches a key shortcut event.
6505     *
6506     * @param event The key event to be dispatched.
6507     * @return True if the event was handled by the view, false otherwise.
6508     */
6509    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6510        return onKeyShortcut(event.getKeyCode(), event);
6511    }
6512
6513    /**
6514     * Pass the touch screen motion event down to the target view, or this
6515     * view if it is the target.
6516     *
6517     * @param event The motion event to be dispatched.
6518     * @return True if the event was handled by the view, false otherwise.
6519     */
6520    public boolean dispatchTouchEvent(MotionEvent event) {
6521        if (mInputEventConsistencyVerifier != null) {
6522            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6523        }
6524
6525        if (onFilterTouchEventForSecurity(event)) {
6526            //noinspection SimplifiableIfStatement
6527            ListenerInfo li = mListenerInfo;
6528            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6529                    && li.mOnTouchListener.onTouch(this, event)) {
6530                return true;
6531            }
6532
6533            if (onTouchEvent(event)) {
6534                return true;
6535            }
6536        }
6537
6538        if (mInputEventConsistencyVerifier != null) {
6539            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6540        }
6541        return false;
6542    }
6543
6544    /**
6545     * Filter the touch event to apply security policies.
6546     *
6547     * @param event The motion event to be filtered.
6548     * @return True if the event should be dispatched, false if the event should be dropped.
6549     *
6550     * @see #getFilterTouchesWhenObscured
6551     */
6552    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6553        //noinspection RedundantIfStatement
6554        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6555                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6556            // Window is obscured, drop this touch.
6557            return false;
6558        }
6559        return true;
6560    }
6561
6562    /**
6563     * Pass a trackball motion event down to the focused view.
6564     *
6565     * @param event The motion event to be dispatched.
6566     * @return True if the event was handled by the view, false otherwise.
6567     */
6568    public boolean dispatchTrackballEvent(MotionEvent event) {
6569        if (mInputEventConsistencyVerifier != null) {
6570            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6571        }
6572
6573        return onTrackballEvent(event);
6574    }
6575
6576    /**
6577     * Dispatch a generic motion event.
6578     * <p>
6579     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6580     * are delivered to the view under the pointer.  All other generic motion events are
6581     * delivered to the focused view.  Hover events are handled specially and are delivered
6582     * to {@link #onHoverEvent(MotionEvent)}.
6583     * </p>
6584     *
6585     * @param event The motion event to be dispatched.
6586     * @return True if the event was handled by the view, false otherwise.
6587     */
6588    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6589        if (mInputEventConsistencyVerifier != null) {
6590            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6591        }
6592
6593        final int source = event.getSource();
6594        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6595            final int action = event.getAction();
6596            if (action == MotionEvent.ACTION_HOVER_ENTER
6597                    || action == MotionEvent.ACTION_HOVER_MOVE
6598                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6599                if (dispatchHoverEvent(event)) {
6600                    return true;
6601                }
6602            } else if (dispatchGenericPointerEvent(event)) {
6603                return true;
6604            }
6605        } else if (dispatchGenericFocusedEvent(event)) {
6606            return true;
6607        }
6608
6609        if (dispatchGenericMotionEventInternal(event)) {
6610            return true;
6611        }
6612
6613        if (mInputEventConsistencyVerifier != null) {
6614            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6615        }
6616        return false;
6617    }
6618
6619    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6620        //noinspection SimplifiableIfStatement
6621        ListenerInfo li = mListenerInfo;
6622        if (li != null && li.mOnGenericMotionListener != null
6623                && (mViewFlags & ENABLED_MASK) == ENABLED
6624                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6625            return true;
6626        }
6627
6628        if (onGenericMotionEvent(event)) {
6629            return true;
6630        }
6631
6632        if (mInputEventConsistencyVerifier != null) {
6633            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6634        }
6635        return false;
6636    }
6637
6638    /**
6639     * Dispatch a hover event.
6640     * <p>
6641     * Do not call this method directly.
6642     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6643     * </p>
6644     *
6645     * @param event The motion event to be dispatched.
6646     * @return True if the event was handled by the view, false otherwise.
6647     */
6648    protected boolean dispatchHoverEvent(MotionEvent event) {
6649        //noinspection SimplifiableIfStatement
6650        ListenerInfo li = mListenerInfo;
6651        if (li != null && li.mOnHoverListener != null
6652                && (mViewFlags & ENABLED_MASK) == ENABLED
6653                && li.mOnHoverListener.onHover(this, event)) {
6654            return true;
6655        }
6656
6657        return onHoverEvent(event);
6658    }
6659
6660    /**
6661     * Returns true if the view has a child to which it has recently sent
6662     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6663     * it does not have a hovered child, then it must be the innermost hovered view.
6664     * @hide
6665     */
6666    protected boolean hasHoveredChild() {
6667        return false;
6668    }
6669
6670    /**
6671     * Dispatch a generic motion event to the view under the first pointer.
6672     * <p>
6673     * Do not call this method directly.
6674     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6675     * </p>
6676     *
6677     * @param event The motion event to be dispatched.
6678     * @return True if the event was handled by the view, false otherwise.
6679     */
6680    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6681        return false;
6682    }
6683
6684    /**
6685     * Dispatch a generic motion event to the currently focused view.
6686     * <p>
6687     * Do not call this method directly.
6688     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6689     * </p>
6690     *
6691     * @param event The motion event to be dispatched.
6692     * @return True if the event was handled by the view, false otherwise.
6693     */
6694    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6695        return false;
6696    }
6697
6698    /**
6699     * Dispatch a pointer event.
6700     * <p>
6701     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
6702     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
6703     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
6704     * and should not be expected to handle other pointing device features.
6705     * </p>
6706     *
6707     * @param event The motion event to be dispatched.
6708     * @return True if the event was handled by the view, false otherwise.
6709     * @hide
6710     */
6711    public final boolean dispatchPointerEvent(MotionEvent event) {
6712        if (event.isTouchEvent()) {
6713            return dispatchTouchEvent(event);
6714        } else {
6715            return dispatchGenericMotionEvent(event);
6716        }
6717    }
6718
6719    /**
6720     * Called when the window containing this view gains or loses window focus.
6721     * ViewGroups should override to route to their children.
6722     *
6723     * @param hasFocus True if the window containing this view now has focus,
6724     *        false otherwise.
6725     */
6726    public void dispatchWindowFocusChanged(boolean hasFocus) {
6727        onWindowFocusChanged(hasFocus);
6728    }
6729
6730    /**
6731     * Called when the window containing this view gains or loses focus.  Note
6732     * that this is separate from view focus: to receive key events, both
6733     * your view and its window must have focus.  If a window is displayed
6734     * on top of yours that takes input focus, then your own window will lose
6735     * focus but the view focus will remain unchanged.
6736     *
6737     * @param hasWindowFocus True if the window containing this view now has
6738     *        focus, false otherwise.
6739     */
6740    public void onWindowFocusChanged(boolean hasWindowFocus) {
6741        InputMethodManager imm = InputMethodManager.peekInstance();
6742        if (!hasWindowFocus) {
6743            if (isPressed()) {
6744                setPressed(false);
6745            }
6746            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6747                imm.focusOut(this);
6748            }
6749            removeLongPressCallback();
6750            removeTapCallback();
6751            onFocusLost();
6752        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6753            imm.focusIn(this);
6754        }
6755        refreshDrawableState();
6756    }
6757
6758    /**
6759     * Returns true if this view is in a window that currently has window focus.
6760     * Note that this is not the same as the view itself having focus.
6761     *
6762     * @return True if this view is in a window that currently has window focus.
6763     */
6764    public boolean hasWindowFocus() {
6765        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
6766    }
6767
6768    /**
6769     * Dispatch a view visibility change down the view hierarchy.
6770     * ViewGroups should override to route to their children.
6771     * @param changedView The view whose visibility changed. Could be 'this' or
6772     * an ancestor view.
6773     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6774     * {@link #INVISIBLE} or {@link #GONE}.
6775     */
6776    protected void dispatchVisibilityChanged(View changedView, int visibility) {
6777        onVisibilityChanged(changedView, visibility);
6778    }
6779
6780    /**
6781     * Called when the visibility of the view or an ancestor of the view is changed.
6782     * @param changedView The view whose visibility changed. Could be 'this' or
6783     * an ancestor view.
6784     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6785     * {@link #INVISIBLE} or {@link #GONE}.
6786     */
6787    protected void onVisibilityChanged(View changedView, int visibility) {
6788        if (visibility == VISIBLE) {
6789            if (mAttachInfo != null) {
6790                initialAwakenScrollBars();
6791            } else {
6792                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
6793            }
6794        }
6795    }
6796
6797    /**
6798     * Dispatch a hint about whether this view is displayed. For instance, when
6799     * a View moves out of the screen, it might receives a display hint indicating
6800     * the view is not displayed. Applications should not <em>rely</em> on this hint
6801     * as there is no guarantee that they will receive one.
6802     *
6803     * @param hint A hint about whether or not this view is displayed:
6804     * {@link #VISIBLE} or {@link #INVISIBLE}.
6805     */
6806    public void dispatchDisplayHint(int hint) {
6807        onDisplayHint(hint);
6808    }
6809
6810    /**
6811     * Gives this view a hint about whether is displayed or not. For instance, when
6812     * a View moves out of the screen, it might receives a display hint indicating
6813     * the view is not displayed. Applications should not <em>rely</em> on this hint
6814     * as there is no guarantee that they will receive one.
6815     *
6816     * @param hint A hint about whether or not this view is displayed:
6817     * {@link #VISIBLE} or {@link #INVISIBLE}.
6818     */
6819    protected void onDisplayHint(int hint) {
6820    }
6821
6822    /**
6823     * Dispatch a window visibility change down the view hierarchy.
6824     * ViewGroups should override to route to their children.
6825     *
6826     * @param visibility The new visibility of the window.
6827     *
6828     * @see #onWindowVisibilityChanged(int)
6829     */
6830    public void dispatchWindowVisibilityChanged(int visibility) {
6831        onWindowVisibilityChanged(visibility);
6832    }
6833
6834    /**
6835     * Called when the window containing has change its visibility
6836     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6837     * that this tells you whether or not your window is being made visible
6838     * to the window manager; this does <em>not</em> tell you whether or not
6839     * your window is obscured by other windows on the screen, even if it
6840     * is itself visible.
6841     *
6842     * @param visibility The new visibility of the window.
6843     */
6844    protected void onWindowVisibilityChanged(int visibility) {
6845        if (visibility == VISIBLE) {
6846            initialAwakenScrollBars();
6847        }
6848    }
6849
6850    /**
6851     * Returns the current visibility of the window this view is attached to
6852     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6853     *
6854     * @return Returns the current visibility of the view's window.
6855     */
6856    public int getWindowVisibility() {
6857        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6858    }
6859
6860    /**
6861     * Retrieve the overall visible display size in which the window this view is
6862     * attached to has been positioned in.  This takes into account screen
6863     * decorations above the window, for both cases where the window itself
6864     * is being position inside of them or the window is being placed under
6865     * then and covered insets are used for the window to position its content
6866     * inside.  In effect, this tells you the available area where content can
6867     * be placed and remain visible to users.
6868     *
6869     * <p>This function requires an IPC back to the window manager to retrieve
6870     * the requested information, so should not be used in performance critical
6871     * code like drawing.
6872     *
6873     * @param outRect Filled in with the visible display frame.  If the view
6874     * is not attached to a window, this is simply the raw display size.
6875     */
6876    public void getWindowVisibleDisplayFrame(Rect outRect) {
6877        if (mAttachInfo != null) {
6878            try {
6879                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6880            } catch (RemoteException e) {
6881                return;
6882            }
6883            // XXX This is really broken, and probably all needs to be done
6884            // in the window manager, and we need to know more about whether
6885            // we want the area behind or in front of the IME.
6886            final Rect insets = mAttachInfo.mVisibleInsets;
6887            outRect.left += insets.left;
6888            outRect.top += insets.top;
6889            outRect.right -= insets.right;
6890            outRect.bottom -= insets.bottom;
6891            return;
6892        }
6893        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6894        d.getRectSize(outRect);
6895    }
6896
6897    /**
6898     * Dispatch a notification about a resource configuration change down
6899     * the view hierarchy.
6900     * ViewGroups should override to route to their children.
6901     *
6902     * @param newConfig The new resource configuration.
6903     *
6904     * @see #onConfigurationChanged(android.content.res.Configuration)
6905     */
6906    public void dispatchConfigurationChanged(Configuration newConfig) {
6907        onConfigurationChanged(newConfig);
6908    }
6909
6910    /**
6911     * Called when the current configuration of the resources being used
6912     * by the application have changed.  You can use this to decide when
6913     * to reload resources that can changed based on orientation and other
6914     * configuration characterstics.  You only need to use this if you are
6915     * not relying on the normal {@link android.app.Activity} mechanism of
6916     * recreating the activity instance upon a configuration change.
6917     *
6918     * @param newConfig The new resource configuration.
6919     */
6920    protected void onConfigurationChanged(Configuration newConfig) {
6921    }
6922
6923    /**
6924     * Private function to aggregate all per-view attributes in to the view
6925     * root.
6926     */
6927    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6928        performCollectViewAttributes(attachInfo, visibility);
6929    }
6930
6931    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
6932        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
6933            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6934                attachInfo.mKeepScreenOn = true;
6935            }
6936            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6937            ListenerInfo li = mListenerInfo;
6938            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6939                attachInfo.mHasSystemUiListeners = true;
6940            }
6941        }
6942    }
6943
6944    void needGlobalAttributesUpdate(boolean force) {
6945        final AttachInfo ai = mAttachInfo;
6946        if (ai != null) {
6947            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6948                    || ai.mHasSystemUiListeners) {
6949                ai.mRecomputeGlobalAttributes = true;
6950            }
6951        }
6952    }
6953
6954    /**
6955     * Returns whether the device is currently in touch mode.  Touch mode is entered
6956     * once the user begins interacting with the device by touch, and affects various
6957     * things like whether focus is always visible to the user.
6958     *
6959     * @return Whether the device is in touch mode.
6960     */
6961    @ViewDebug.ExportedProperty
6962    public boolean isInTouchMode() {
6963        if (mAttachInfo != null) {
6964            return mAttachInfo.mInTouchMode;
6965        } else {
6966            return ViewRootImpl.isInTouchMode();
6967        }
6968    }
6969
6970    /**
6971     * Returns the context the view is running in, through which it can
6972     * access the current theme, resources, etc.
6973     *
6974     * @return The view's Context.
6975     */
6976    @ViewDebug.CapturedViewProperty
6977    public final Context getContext() {
6978        return mContext;
6979    }
6980
6981    /**
6982     * Handle a key event before it is processed by any input method
6983     * associated with the view hierarchy.  This can be used to intercept
6984     * key events in special situations before the IME consumes them; a
6985     * typical example would be handling the BACK key to update the application's
6986     * UI instead of allowing the IME to see it and close itself.
6987     *
6988     * @param keyCode The value in event.getKeyCode().
6989     * @param event Description of the key event.
6990     * @return If you handled the event, return true. If you want to allow the
6991     *         event to be handled by the next receiver, return false.
6992     */
6993    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6994        return false;
6995    }
6996
6997    /**
6998     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6999     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7000     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7001     * is released, if the view is enabled and clickable.
7002     *
7003     * @param keyCode A key code that represents the button pressed, from
7004     *                {@link android.view.KeyEvent}.
7005     * @param event   The KeyEvent object that defines the button action.
7006     */
7007    public boolean onKeyDown(int keyCode, KeyEvent event) {
7008        boolean result = false;
7009
7010        switch (keyCode) {
7011            case KeyEvent.KEYCODE_DPAD_CENTER:
7012            case KeyEvent.KEYCODE_ENTER: {
7013                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7014                    return true;
7015                }
7016                // Long clickable items don't necessarily have to be clickable
7017                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7018                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7019                        (event.getRepeatCount() == 0)) {
7020                    setPressed(true);
7021                    checkForLongClick(0);
7022                    return true;
7023                }
7024                break;
7025            }
7026        }
7027        return result;
7028    }
7029
7030    /**
7031     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7032     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7033     * the event).
7034     */
7035    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7036        return false;
7037    }
7038
7039    /**
7040     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7041     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7042     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7043     * {@link KeyEvent#KEYCODE_ENTER} is released.
7044     *
7045     * @param keyCode A key code that represents the button pressed, from
7046     *                {@link android.view.KeyEvent}.
7047     * @param event   The KeyEvent object that defines the button action.
7048     */
7049    public boolean onKeyUp(int keyCode, KeyEvent event) {
7050        boolean result = false;
7051
7052        switch (keyCode) {
7053            case KeyEvent.KEYCODE_DPAD_CENTER:
7054            case KeyEvent.KEYCODE_ENTER: {
7055                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7056                    return true;
7057                }
7058                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7059                    setPressed(false);
7060
7061                    if (!mHasPerformedLongPress) {
7062                        // This is a tap, so remove the longpress check
7063                        removeLongPressCallback();
7064
7065                        result = performClick();
7066                    }
7067                }
7068                break;
7069            }
7070        }
7071        return result;
7072    }
7073
7074    /**
7075     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7076     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7077     * the event).
7078     *
7079     * @param keyCode     A key code that represents the button pressed, from
7080     *                    {@link android.view.KeyEvent}.
7081     * @param repeatCount The number of times the action was made.
7082     * @param event       The KeyEvent object that defines the button action.
7083     */
7084    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7085        return false;
7086    }
7087
7088    /**
7089     * Called on the focused view when a key shortcut event is not handled.
7090     * Override this method to implement local key shortcuts for the View.
7091     * Key shortcuts can also be implemented by setting the
7092     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7093     *
7094     * @param keyCode The value in event.getKeyCode().
7095     * @param event Description of the key event.
7096     * @return If you handled the event, return true. If you want to allow the
7097     *         event to be handled by the next receiver, return false.
7098     */
7099    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7100        return false;
7101    }
7102
7103    /**
7104     * Check whether the called view is a text editor, in which case it
7105     * would make sense to automatically display a soft input window for
7106     * it.  Subclasses should override this if they implement
7107     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7108     * a call on that method would return a non-null InputConnection, and
7109     * they are really a first-class editor that the user would normally
7110     * start typing on when the go into a window containing your view.
7111     *
7112     * <p>The default implementation always returns false.  This does
7113     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7114     * will not be called or the user can not otherwise perform edits on your
7115     * view; it is just a hint to the system that this is not the primary
7116     * purpose of this view.
7117     *
7118     * @return Returns true if this view is a text editor, else false.
7119     */
7120    public boolean onCheckIsTextEditor() {
7121        return false;
7122    }
7123
7124    /**
7125     * Create a new InputConnection for an InputMethod to interact
7126     * with the view.  The default implementation returns null, since it doesn't
7127     * support input methods.  You can override this to implement such support.
7128     * This is only needed for views that take focus and text input.
7129     *
7130     * <p>When implementing this, you probably also want to implement
7131     * {@link #onCheckIsTextEditor()} to indicate you will return a
7132     * non-null InputConnection.
7133     *
7134     * @param outAttrs Fill in with attribute information about the connection.
7135     */
7136    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7137        return null;
7138    }
7139
7140    /**
7141     * Called by the {@link android.view.inputmethod.InputMethodManager}
7142     * when a view who is not the current
7143     * input connection target is trying to make a call on the manager.  The
7144     * default implementation returns false; you can override this to return
7145     * true for certain views if you are performing InputConnection proxying
7146     * to them.
7147     * @param view The View that is making the InputMethodManager call.
7148     * @return Return true to allow the call, false to reject.
7149     */
7150    public boolean checkInputConnectionProxy(View view) {
7151        return false;
7152    }
7153
7154    /**
7155     * Show the context menu for this view. It is not safe to hold on to the
7156     * menu after returning from this method.
7157     *
7158     * You should normally not overload this method. Overload
7159     * {@link #onCreateContextMenu(ContextMenu)} or define an
7160     * {@link OnCreateContextMenuListener} to add items to the context menu.
7161     *
7162     * @param menu The context menu to populate
7163     */
7164    public void createContextMenu(ContextMenu menu) {
7165        ContextMenuInfo menuInfo = getContextMenuInfo();
7166
7167        // Sets the current menu info so all items added to menu will have
7168        // my extra info set.
7169        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7170
7171        onCreateContextMenu(menu);
7172        ListenerInfo li = mListenerInfo;
7173        if (li != null && li.mOnCreateContextMenuListener != null) {
7174            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7175        }
7176
7177        // Clear the extra information so subsequent items that aren't mine don't
7178        // have my extra info.
7179        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7180
7181        if (mParent != null) {
7182            mParent.createContextMenu(menu);
7183        }
7184    }
7185
7186    /**
7187     * Views should implement this if they have extra information to associate
7188     * with the context menu. The return result is supplied as a parameter to
7189     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7190     * callback.
7191     *
7192     * @return Extra information about the item for which the context menu
7193     *         should be shown. This information will vary across different
7194     *         subclasses of View.
7195     */
7196    protected ContextMenuInfo getContextMenuInfo() {
7197        return null;
7198    }
7199
7200    /**
7201     * Views should implement this if the view itself is going to add items to
7202     * the context menu.
7203     *
7204     * @param menu the context menu to populate
7205     */
7206    protected void onCreateContextMenu(ContextMenu menu) {
7207    }
7208
7209    /**
7210     * Implement this method to handle trackball motion events.  The
7211     * <em>relative</em> movement of the trackball since the last event
7212     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7213     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7214     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7215     * they will often be fractional values, representing the more fine-grained
7216     * movement information available from a trackball).
7217     *
7218     * @param event The motion event.
7219     * @return True if the event was handled, false otherwise.
7220     */
7221    public boolean onTrackballEvent(MotionEvent event) {
7222        return false;
7223    }
7224
7225    /**
7226     * Implement this method to handle generic motion events.
7227     * <p>
7228     * Generic motion events describe joystick movements, mouse hovers, track pad
7229     * touches, scroll wheel movements and other input events.  The
7230     * {@link MotionEvent#getSource() source} of the motion event specifies
7231     * the class of input that was received.  Implementations of this method
7232     * must examine the bits in the source before processing the event.
7233     * The following code example shows how this is done.
7234     * </p><p>
7235     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7236     * are delivered to the view under the pointer.  All other generic motion events are
7237     * delivered to the focused view.
7238     * </p>
7239     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7240     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7241     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7242     *             // process the joystick movement...
7243     *             return true;
7244     *         }
7245     *     }
7246     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7247     *         switch (event.getAction()) {
7248     *             case MotionEvent.ACTION_HOVER_MOVE:
7249     *                 // process the mouse hover movement...
7250     *                 return true;
7251     *             case MotionEvent.ACTION_SCROLL:
7252     *                 // process the scroll wheel movement...
7253     *                 return true;
7254     *         }
7255     *     }
7256     *     return super.onGenericMotionEvent(event);
7257     * }</pre>
7258     *
7259     * @param event The generic motion event being processed.
7260     * @return True if the event was handled, false otherwise.
7261     */
7262    public boolean onGenericMotionEvent(MotionEvent event) {
7263        return false;
7264    }
7265
7266    /**
7267     * Implement this method to handle hover events.
7268     * <p>
7269     * This method is called whenever a pointer is hovering into, over, or out of the
7270     * bounds of a view and the view is not currently being touched.
7271     * Hover events are represented as pointer events with action
7272     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7273     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7274     * </p>
7275     * <ul>
7276     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7277     * when the pointer enters the bounds of the view.</li>
7278     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7279     * when the pointer has already entered the bounds of the view and has moved.</li>
7280     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7281     * when the pointer has exited the bounds of the view or when the pointer is
7282     * about to go down due to a button click, tap, or similar user action that
7283     * causes the view to be touched.</li>
7284     * </ul>
7285     * <p>
7286     * The view should implement this method to return true to indicate that it is
7287     * handling the hover event, such as by changing its drawable state.
7288     * </p><p>
7289     * The default implementation calls {@link #setHovered} to update the hovered state
7290     * of the view when a hover enter or hover exit event is received, if the view
7291     * is enabled and is clickable.  The default implementation also sends hover
7292     * accessibility events.
7293     * </p>
7294     *
7295     * @param event The motion event that describes the hover.
7296     * @return True if the view handled the hover event.
7297     *
7298     * @see #isHovered
7299     * @see #setHovered
7300     * @see #onHoverChanged
7301     */
7302    public boolean onHoverEvent(MotionEvent event) {
7303        // The root view may receive hover (or touch) events that are outside the bounds of
7304        // the window.  This code ensures that we only send accessibility events for
7305        // hovers that are actually within the bounds of the root view.
7306        final int action = event.getActionMasked();
7307        if (!mSendingHoverAccessibilityEvents) {
7308            if ((action == MotionEvent.ACTION_HOVER_ENTER
7309                    || action == MotionEvent.ACTION_HOVER_MOVE)
7310                    && !hasHoveredChild()
7311                    && pointInView(event.getX(), event.getY())) {
7312                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7313                mSendingHoverAccessibilityEvents = true;
7314                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7315            }
7316        } else {
7317            if (action == MotionEvent.ACTION_HOVER_EXIT
7318                    || (action == MotionEvent.ACTION_MOVE
7319                            && !pointInView(event.getX(), event.getY()))) {
7320                mSendingHoverAccessibilityEvents = false;
7321                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7322                // If the window does not have input focus we take away accessibility
7323                // focus as soon as the user stop hovering over the view.
7324                if (!mAttachInfo.mHasWindowFocus) {
7325                    getViewRootImpl().setAccessibilityFocusedHost(null);
7326                }
7327            }
7328        }
7329
7330        if (isHoverable()) {
7331            switch (action) {
7332                case MotionEvent.ACTION_HOVER_ENTER:
7333                    setHovered(true);
7334                    break;
7335                case MotionEvent.ACTION_HOVER_EXIT:
7336                    setHovered(false);
7337                    break;
7338            }
7339
7340            // Dispatch the event to onGenericMotionEvent before returning true.
7341            // This is to provide compatibility with existing applications that
7342            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7343            // break because of the new default handling for hoverable views
7344            // in onHoverEvent.
7345            // Note that onGenericMotionEvent will be called by default when
7346            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7347            dispatchGenericMotionEventInternal(event);
7348            return true;
7349        }
7350
7351        return false;
7352    }
7353
7354    /**
7355     * Returns true if the view should handle {@link #onHoverEvent}
7356     * by calling {@link #setHovered} to change its hovered state.
7357     *
7358     * @return True if the view is hoverable.
7359     */
7360    private boolean isHoverable() {
7361        final int viewFlags = mViewFlags;
7362        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7363            return false;
7364        }
7365
7366        return (viewFlags & CLICKABLE) == CLICKABLE
7367                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7368    }
7369
7370    /**
7371     * Returns true if the view is currently hovered.
7372     *
7373     * @return True if the view is currently hovered.
7374     *
7375     * @see #setHovered
7376     * @see #onHoverChanged
7377     */
7378    @ViewDebug.ExportedProperty
7379    public boolean isHovered() {
7380        return (mPrivateFlags & HOVERED) != 0;
7381    }
7382
7383    /**
7384     * Sets whether the view is currently hovered.
7385     * <p>
7386     * Calling this method also changes the drawable state of the view.  This
7387     * enables the view to react to hover by using different drawable resources
7388     * to change its appearance.
7389     * </p><p>
7390     * The {@link #onHoverChanged} method is called when the hovered state changes.
7391     * </p>
7392     *
7393     * @param hovered True if the view is hovered.
7394     *
7395     * @see #isHovered
7396     * @see #onHoverChanged
7397     */
7398    public void setHovered(boolean hovered) {
7399        if (hovered) {
7400            if ((mPrivateFlags & HOVERED) == 0) {
7401                mPrivateFlags |= HOVERED;
7402                refreshDrawableState();
7403                onHoverChanged(true);
7404            }
7405        } else {
7406            if ((mPrivateFlags & HOVERED) != 0) {
7407                mPrivateFlags &= ~HOVERED;
7408                refreshDrawableState();
7409                onHoverChanged(false);
7410            }
7411        }
7412    }
7413
7414    /**
7415     * Implement this method to handle hover state changes.
7416     * <p>
7417     * This method is called whenever the hover state changes as a result of a
7418     * call to {@link #setHovered}.
7419     * </p>
7420     *
7421     * @param hovered The current hover state, as returned by {@link #isHovered}.
7422     *
7423     * @see #isHovered
7424     * @see #setHovered
7425     */
7426    public void onHoverChanged(boolean hovered) {
7427    }
7428
7429    /**
7430     * Implement this method to handle touch screen motion events.
7431     *
7432     * @param event The motion event.
7433     * @return True if the event was handled, false otherwise.
7434     */
7435    public boolean onTouchEvent(MotionEvent event) {
7436        final int viewFlags = mViewFlags;
7437
7438        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7439            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7440                setPressed(false);
7441            }
7442            // A disabled view that is clickable still consumes the touch
7443            // events, it just doesn't respond to them.
7444            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7445                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7446        }
7447
7448        if (mTouchDelegate != null) {
7449            if (mTouchDelegate.onTouchEvent(event)) {
7450                return true;
7451            }
7452        }
7453
7454        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7455                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7456            switch (event.getAction()) {
7457                case MotionEvent.ACTION_UP:
7458                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7459                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7460                        // take focus if we don't have it already and we should in
7461                        // touch mode.
7462                        boolean focusTaken = false;
7463                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7464                            focusTaken = requestFocus();
7465                        }
7466
7467                        if (prepressed) {
7468                            // The button is being released before we actually
7469                            // showed it as pressed.  Make it show the pressed
7470                            // state now (before scheduling the click) to ensure
7471                            // the user sees it.
7472                            setPressed(true);
7473                       }
7474
7475                        if (!mHasPerformedLongPress) {
7476                            // This is a tap, so remove the longpress check
7477                            removeLongPressCallback();
7478
7479                            // Only perform take click actions if we were in the pressed state
7480                            if (!focusTaken) {
7481                                // Use a Runnable and post this rather than calling
7482                                // performClick directly. This lets other visual state
7483                                // of the view update before click actions start.
7484                                if (mPerformClick == null) {
7485                                    mPerformClick = new PerformClick();
7486                                }
7487                                if (!post(mPerformClick)) {
7488                                    performClick();
7489                                }
7490                            }
7491                        }
7492
7493                        if (mUnsetPressedState == null) {
7494                            mUnsetPressedState = new UnsetPressedState();
7495                        }
7496
7497                        if (prepressed) {
7498                            postDelayed(mUnsetPressedState,
7499                                    ViewConfiguration.getPressedStateDuration());
7500                        } else if (!post(mUnsetPressedState)) {
7501                            // If the post failed, unpress right now
7502                            mUnsetPressedState.run();
7503                        }
7504                        removeTapCallback();
7505                    }
7506                    break;
7507
7508                case MotionEvent.ACTION_DOWN:
7509                    mHasPerformedLongPress = false;
7510
7511                    if (performButtonActionOnTouchDown(event)) {
7512                        break;
7513                    }
7514
7515                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7516                    boolean isInScrollingContainer = isInScrollingContainer();
7517
7518                    // For views inside a scrolling container, delay the pressed feedback for
7519                    // a short period in case this is a scroll.
7520                    if (isInScrollingContainer) {
7521                        mPrivateFlags |= PREPRESSED;
7522                        if (mPendingCheckForTap == null) {
7523                            mPendingCheckForTap = new CheckForTap();
7524                        }
7525                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7526                    } else {
7527                        // Not inside a scrolling container, so show the feedback right away
7528                        setPressed(true);
7529                        checkForLongClick(0);
7530                    }
7531                    break;
7532
7533                case MotionEvent.ACTION_CANCEL:
7534                    setPressed(false);
7535                    removeTapCallback();
7536                    break;
7537
7538                case MotionEvent.ACTION_MOVE:
7539                    final int x = (int) event.getX();
7540                    final int y = (int) event.getY();
7541
7542                    // Be lenient about moving outside of buttons
7543                    if (!pointInView(x, y, mTouchSlop)) {
7544                        // Outside button
7545                        removeTapCallback();
7546                        if ((mPrivateFlags & PRESSED) != 0) {
7547                            // Remove any future long press/tap checks
7548                            removeLongPressCallback();
7549
7550                            setPressed(false);
7551                        }
7552                    }
7553                    break;
7554            }
7555            return true;
7556        }
7557
7558        return false;
7559    }
7560
7561    /**
7562     * @hide
7563     */
7564    public boolean isInScrollingContainer() {
7565        ViewParent p = getParent();
7566        while (p != null && p instanceof ViewGroup) {
7567            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7568                return true;
7569            }
7570            p = p.getParent();
7571        }
7572        return false;
7573    }
7574
7575    /**
7576     * Remove the longpress detection timer.
7577     */
7578    private void removeLongPressCallback() {
7579        if (mPendingCheckForLongPress != null) {
7580          removeCallbacks(mPendingCheckForLongPress);
7581        }
7582    }
7583
7584    /**
7585     * Remove the pending click action
7586     */
7587    private void removePerformClickCallback() {
7588        if (mPerformClick != null) {
7589            removeCallbacks(mPerformClick);
7590        }
7591    }
7592
7593    /**
7594     * Remove the prepress detection timer.
7595     */
7596    private void removeUnsetPressCallback() {
7597        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7598            setPressed(false);
7599            removeCallbacks(mUnsetPressedState);
7600        }
7601    }
7602
7603    /**
7604     * Remove the tap detection timer.
7605     */
7606    private void removeTapCallback() {
7607        if (mPendingCheckForTap != null) {
7608            mPrivateFlags &= ~PREPRESSED;
7609            removeCallbacks(mPendingCheckForTap);
7610        }
7611    }
7612
7613    /**
7614     * Cancels a pending long press.  Your subclass can use this if you
7615     * want the context menu to come up if the user presses and holds
7616     * at the same place, but you don't want it to come up if they press
7617     * and then move around enough to cause scrolling.
7618     */
7619    public void cancelLongPress() {
7620        removeLongPressCallback();
7621
7622        /*
7623         * The prepressed state handled by the tap callback is a display
7624         * construct, but the tap callback will post a long press callback
7625         * less its own timeout. Remove it here.
7626         */
7627        removeTapCallback();
7628    }
7629
7630    /**
7631     * Remove the pending callback for sending a
7632     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7633     */
7634    private void removeSendViewScrolledAccessibilityEventCallback() {
7635        if (mSendViewScrolledAccessibilityEvent != null) {
7636            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7637        }
7638    }
7639
7640    /**
7641     * Sets the TouchDelegate for this View.
7642     */
7643    public void setTouchDelegate(TouchDelegate delegate) {
7644        mTouchDelegate = delegate;
7645    }
7646
7647    /**
7648     * Gets the TouchDelegate for this View.
7649     */
7650    public TouchDelegate getTouchDelegate() {
7651        return mTouchDelegate;
7652    }
7653
7654    /**
7655     * Set flags controlling behavior of this view.
7656     *
7657     * @param flags Constant indicating the value which should be set
7658     * @param mask Constant indicating the bit range that should be changed
7659     */
7660    void setFlags(int flags, int mask) {
7661        int old = mViewFlags;
7662        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7663
7664        int changed = mViewFlags ^ old;
7665        if (changed == 0) {
7666            return;
7667        }
7668        int privateFlags = mPrivateFlags;
7669
7670        /* Check if the FOCUSABLE bit has changed */
7671        if (((changed & FOCUSABLE_MASK) != 0) &&
7672                ((privateFlags & HAS_BOUNDS) !=0)) {
7673            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7674                    && ((privateFlags & FOCUSED) != 0)) {
7675                /* Give up focus if we are no longer focusable */
7676                clearFocus();
7677            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7678                    && ((privateFlags & FOCUSED) == 0)) {
7679                /*
7680                 * Tell the view system that we are now available to take focus
7681                 * if no one else already has it.
7682                 */
7683                if (mParent != null) mParent.focusableViewAvailable(this);
7684            }
7685            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7686                notifyAccessibilityStateChanged();
7687            }
7688        }
7689
7690        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7691            if ((changed & VISIBILITY_MASK) != 0) {
7692                /*
7693                 * If this view is becoming visible, invalidate it in case it changed while
7694                 * it was not visible. Marking it drawn ensures that the invalidation will
7695                 * go through.
7696                 */
7697                mPrivateFlags |= DRAWN;
7698                invalidate(true);
7699
7700                needGlobalAttributesUpdate(true);
7701
7702                // a view becoming visible is worth notifying the parent
7703                // about in case nothing has focus.  even if this specific view
7704                // isn't focusable, it may contain something that is, so let
7705                // the root view try to give this focus if nothing else does.
7706                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
7707                    mParent.focusableViewAvailable(this);
7708                }
7709            }
7710        }
7711
7712        /* Check if the GONE bit has changed */
7713        if ((changed & GONE) != 0) {
7714            needGlobalAttributesUpdate(false);
7715            requestLayout();
7716
7717            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
7718                if (hasFocus()) clearFocus();
7719                clearAccessibilityFocus();
7720                destroyDrawingCache();
7721                if (mParent instanceof View) {
7722                    // GONE views noop invalidation, so invalidate the parent
7723                    ((View) mParent).invalidate(true);
7724                }
7725                // Mark the view drawn to ensure that it gets invalidated properly the next
7726                // time it is visible and gets invalidated
7727                mPrivateFlags |= DRAWN;
7728            }
7729            if (mAttachInfo != null) {
7730                mAttachInfo.mViewVisibilityChanged = true;
7731            }
7732        }
7733
7734        /* Check if the VISIBLE bit has changed */
7735        if ((changed & INVISIBLE) != 0) {
7736            needGlobalAttributesUpdate(false);
7737            /*
7738             * If this view is becoming invisible, set the DRAWN flag so that
7739             * the next invalidate() will not be skipped.
7740             */
7741            mPrivateFlags |= DRAWN;
7742
7743            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
7744                // root view becoming invisible shouldn't clear focus and accessibility focus
7745                if (getRootView() != this) {
7746                    clearFocus();
7747                    clearAccessibilityFocus();
7748                }
7749            }
7750            if (mAttachInfo != null) {
7751                mAttachInfo.mViewVisibilityChanged = true;
7752            }
7753        }
7754
7755        if ((changed & VISIBILITY_MASK) != 0) {
7756            if (mParent instanceof ViewGroup) {
7757                ((ViewGroup) mParent).onChildVisibilityChanged(this,
7758                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
7759                ((View) mParent).invalidate(true);
7760            } else if (mParent != null) {
7761                mParent.invalidateChild(this, null);
7762            }
7763            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
7764        }
7765
7766        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
7767            destroyDrawingCache();
7768        }
7769
7770        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
7771            destroyDrawingCache();
7772            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7773            invalidateParentCaches();
7774        }
7775
7776        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
7777            destroyDrawingCache();
7778            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7779        }
7780
7781        if ((changed & DRAW_MASK) != 0) {
7782            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
7783                if (mBackground != null) {
7784                    mPrivateFlags &= ~SKIP_DRAW;
7785                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7786                } else {
7787                    mPrivateFlags |= SKIP_DRAW;
7788                }
7789            } else {
7790                mPrivateFlags &= ~SKIP_DRAW;
7791            }
7792            requestLayout();
7793            invalidate(true);
7794        }
7795
7796        if ((changed & KEEP_SCREEN_ON) != 0) {
7797            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
7798                mParent.recomputeViewAttributes(this);
7799            }
7800        }
7801
7802        if (AccessibilityManager.getInstance(mContext).isEnabled()
7803                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
7804                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
7805            notifyAccessibilityStateChanged();
7806        }
7807    }
7808
7809    /**
7810     * Change the view's z order in the tree, so it's on top of other sibling
7811     * views
7812     */
7813    public void bringToFront() {
7814        if (mParent != null) {
7815            mParent.bringChildToFront(this);
7816        }
7817    }
7818
7819    /**
7820     * This is called in response to an internal scroll in this view (i.e., the
7821     * view scrolled its own contents). This is typically as a result of
7822     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
7823     * called.
7824     *
7825     * @param l Current horizontal scroll origin.
7826     * @param t Current vertical scroll origin.
7827     * @param oldl Previous horizontal scroll origin.
7828     * @param oldt Previous vertical scroll origin.
7829     */
7830    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
7831        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7832            postSendViewScrolledAccessibilityEventCallback();
7833        }
7834
7835        mBackgroundSizeChanged = true;
7836
7837        final AttachInfo ai = mAttachInfo;
7838        if (ai != null) {
7839            ai.mViewScrollChanged = true;
7840        }
7841    }
7842
7843    /**
7844     * Interface definition for a callback to be invoked when the layout bounds of a view
7845     * changes due to layout processing.
7846     */
7847    public interface OnLayoutChangeListener {
7848        /**
7849         * Called when the focus state of a view has changed.
7850         *
7851         * @param v The view whose state has changed.
7852         * @param left The new value of the view's left property.
7853         * @param top The new value of the view's top property.
7854         * @param right The new value of the view's right property.
7855         * @param bottom The new value of the view's bottom property.
7856         * @param oldLeft The previous value of the view's left property.
7857         * @param oldTop The previous value of the view's top property.
7858         * @param oldRight The previous value of the view's right property.
7859         * @param oldBottom The previous value of the view's bottom property.
7860         */
7861        void onLayoutChange(View v, int left, int top, int right, int bottom,
7862            int oldLeft, int oldTop, int oldRight, int oldBottom);
7863    }
7864
7865    /**
7866     * This is called during layout when the size of this view has changed. If
7867     * you were just added to the view hierarchy, you're called with the old
7868     * values of 0.
7869     *
7870     * @param w Current width of this view.
7871     * @param h Current height of this view.
7872     * @param oldw Old width of this view.
7873     * @param oldh Old height of this view.
7874     */
7875    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7876    }
7877
7878    /**
7879     * Called by draw to draw the child views. This may be overridden
7880     * by derived classes to gain control just before its children are drawn
7881     * (but after its own view has been drawn).
7882     * @param canvas the canvas on which to draw the view
7883     */
7884    protected void dispatchDraw(Canvas canvas) {
7885
7886    }
7887
7888    /**
7889     * Gets the parent of this view. Note that the parent is a
7890     * ViewParent and not necessarily a View.
7891     *
7892     * @return Parent of this view.
7893     */
7894    public final ViewParent getParent() {
7895        return mParent;
7896    }
7897
7898    /**
7899     * Set the horizontal scrolled position of your view. This will cause a call to
7900     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7901     * invalidated.
7902     * @param value the x position to scroll to
7903     */
7904    public void setScrollX(int value) {
7905        scrollTo(value, mScrollY);
7906    }
7907
7908    /**
7909     * Set the vertical scrolled position of your view. This will cause a call to
7910     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7911     * invalidated.
7912     * @param value the y position to scroll to
7913     */
7914    public void setScrollY(int value) {
7915        scrollTo(mScrollX, value);
7916    }
7917
7918    /**
7919     * Return the scrolled left position of this view. This is the left edge of
7920     * the displayed part of your view. You do not need to draw any pixels
7921     * farther left, since those are outside of the frame of your view on
7922     * screen.
7923     *
7924     * @return The left edge of the displayed part of your view, in pixels.
7925     */
7926    public final int getScrollX() {
7927        return mScrollX;
7928    }
7929
7930    /**
7931     * Return the scrolled top position of this view. This is the top edge of
7932     * the displayed part of your view. You do not need to draw any pixels above
7933     * it, since those are outside of the frame of your view on screen.
7934     *
7935     * @return The top edge of the displayed part of your view, in pixels.
7936     */
7937    public final int getScrollY() {
7938        return mScrollY;
7939    }
7940
7941    /**
7942     * Return the width of the your view.
7943     *
7944     * @return The width of your view, in pixels.
7945     */
7946    @ViewDebug.ExportedProperty(category = "layout")
7947    public final int getWidth() {
7948        return mRight - mLeft;
7949    }
7950
7951    /**
7952     * Return the height of your view.
7953     *
7954     * @return The height of your view, in pixels.
7955     */
7956    @ViewDebug.ExportedProperty(category = "layout")
7957    public final int getHeight() {
7958        return mBottom - mTop;
7959    }
7960
7961    /**
7962     * Return the visible drawing bounds of your view. Fills in the output
7963     * rectangle with the values from getScrollX(), getScrollY(),
7964     * getWidth(), and getHeight().
7965     *
7966     * @param outRect The (scrolled) drawing bounds of the view.
7967     */
7968    public void getDrawingRect(Rect outRect) {
7969        outRect.left = mScrollX;
7970        outRect.top = mScrollY;
7971        outRect.right = mScrollX + (mRight - mLeft);
7972        outRect.bottom = mScrollY + (mBottom - mTop);
7973    }
7974
7975    /**
7976     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7977     * raw width component (that is the result is masked by
7978     * {@link #MEASURED_SIZE_MASK}).
7979     *
7980     * @return The raw measured width of this view.
7981     */
7982    public final int getMeasuredWidth() {
7983        return mMeasuredWidth & MEASURED_SIZE_MASK;
7984    }
7985
7986    /**
7987     * Return the full width measurement information for this view as computed
7988     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7989     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7990     * This should be used during measurement and layout calculations only. Use
7991     * {@link #getWidth()} to see how wide a view is after layout.
7992     *
7993     * @return The measured width of this view as a bit mask.
7994     */
7995    public final int getMeasuredWidthAndState() {
7996        return mMeasuredWidth;
7997    }
7998
7999    /**
8000     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8001     * raw width component (that is the result is masked by
8002     * {@link #MEASURED_SIZE_MASK}).
8003     *
8004     * @return The raw measured height of this view.
8005     */
8006    public final int getMeasuredHeight() {
8007        return mMeasuredHeight & MEASURED_SIZE_MASK;
8008    }
8009
8010    /**
8011     * Return the full height measurement information for this view as computed
8012     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8013     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8014     * This should be used during measurement and layout calculations only. Use
8015     * {@link #getHeight()} to see how wide a view is after layout.
8016     *
8017     * @return The measured width of this view as a bit mask.
8018     */
8019    public final int getMeasuredHeightAndState() {
8020        return mMeasuredHeight;
8021    }
8022
8023    /**
8024     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8025     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8026     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8027     * and the height component is at the shifted bits
8028     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8029     */
8030    public final int getMeasuredState() {
8031        return (mMeasuredWidth&MEASURED_STATE_MASK)
8032                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8033                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8034    }
8035
8036    /**
8037     * The transform matrix of this view, which is calculated based on the current
8038     * roation, scale, and pivot properties.
8039     *
8040     * @see #getRotation()
8041     * @see #getScaleX()
8042     * @see #getScaleY()
8043     * @see #getPivotX()
8044     * @see #getPivotY()
8045     * @return The current transform matrix for the view
8046     */
8047    public Matrix getMatrix() {
8048        if (mTransformationInfo != null) {
8049            updateMatrix();
8050            return mTransformationInfo.mMatrix;
8051        }
8052        return Matrix.IDENTITY_MATRIX;
8053    }
8054
8055    /**
8056     * Utility function to determine if the value is far enough away from zero to be
8057     * considered non-zero.
8058     * @param value A floating point value to check for zero-ness
8059     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8060     */
8061    private static boolean nonzero(float value) {
8062        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8063    }
8064
8065    /**
8066     * Returns true if the transform matrix is the identity matrix.
8067     * Recomputes the matrix if necessary.
8068     *
8069     * @return True if the transform matrix is the identity matrix, false otherwise.
8070     */
8071    final boolean hasIdentityMatrix() {
8072        if (mTransformationInfo != null) {
8073            updateMatrix();
8074            return mTransformationInfo.mMatrixIsIdentity;
8075        }
8076        return true;
8077    }
8078
8079    void ensureTransformationInfo() {
8080        if (mTransformationInfo == null) {
8081            mTransformationInfo = new TransformationInfo();
8082        }
8083    }
8084
8085    /**
8086     * Recomputes the transform matrix if necessary.
8087     */
8088    private void updateMatrix() {
8089        final TransformationInfo info = mTransformationInfo;
8090        if (info == null) {
8091            return;
8092        }
8093        if (info.mMatrixDirty) {
8094            // transform-related properties have changed since the last time someone
8095            // asked for the matrix; recalculate it with the current values
8096
8097            // Figure out if we need to update the pivot point
8098            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8099                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8100                    info.mPrevWidth = mRight - mLeft;
8101                    info.mPrevHeight = mBottom - mTop;
8102                    info.mPivotX = info.mPrevWidth / 2f;
8103                    info.mPivotY = info.mPrevHeight / 2f;
8104                }
8105            }
8106            info.mMatrix.reset();
8107            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8108                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8109                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8110                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8111            } else {
8112                if (info.mCamera == null) {
8113                    info.mCamera = new Camera();
8114                    info.matrix3D = new Matrix();
8115                }
8116                info.mCamera.save();
8117                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8118                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8119                info.mCamera.getMatrix(info.matrix3D);
8120                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8121                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8122                        info.mPivotY + info.mTranslationY);
8123                info.mMatrix.postConcat(info.matrix3D);
8124                info.mCamera.restore();
8125            }
8126            info.mMatrixDirty = false;
8127            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8128            info.mInverseMatrixDirty = true;
8129        }
8130    }
8131
8132    /**
8133     * Utility method to retrieve the inverse of the current mMatrix property.
8134     * We cache the matrix to avoid recalculating it when transform properties
8135     * have not changed.
8136     *
8137     * @return The inverse of the current matrix of this view.
8138     */
8139    final Matrix getInverseMatrix() {
8140        final TransformationInfo info = mTransformationInfo;
8141        if (info != null) {
8142            updateMatrix();
8143            if (info.mInverseMatrixDirty) {
8144                if (info.mInverseMatrix == null) {
8145                    info.mInverseMatrix = new Matrix();
8146                }
8147                info.mMatrix.invert(info.mInverseMatrix);
8148                info.mInverseMatrixDirty = false;
8149            }
8150            return info.mInverseMatrix;
8151        }
8152        return Matrix.IDENTITY_MATRIX;
8153    }
8154
8155    /**
8156     * Gets the distance along the Z axis from the camera to this view.
8157     *
8158     * @see #setCameraDistance(float)
8159     *
8160     * @return The distance along the Z axis.
8161     */
8162    public float getCameraDistance() {
8163        ensureTransformationInfo();
8164        final float dpi = mResources.getDisplayMetrics().densityDpi;
8165        final TransformationInfo info = mTransformationInfo;
8166        if (info.mCamera == null) {
8167            info.mCamera = new Camera();
8168            info.matrix3D = new Matrix();
8169        }
8170        return -(info.mCamera.getLocationZ() * dpi);
8171    }
8172
8173    /**
8174     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8175     * views are drawn) from the camera to this view. The camera's distance
8176     * affects 3D transformations, for instance rotations around the X and Y
8177     * axis. If the rotationX or rotationY properties are changed and this view is
8178     * large (more than half the size of the screen), it is recommended to always
8179     * use a camera distance that's greater than the height (X axis rotation) or
8180     * the width (Y axis rotation) of this view.</p>
8181     *
8182     * <p>The distance of the camera from the view plane can have an affect on the
8183     * perspective distortion of the view when it is rotated around the x or y axis.
8184     * For example, a large distance will result in a large viewing angle, and there
8185     * will not be much perspective distortion of the view as it rotates. A short
8186     * distance may cause much more perspective distortion upon rotation, and can
8187     * also result in some drawing artifacts if the rotated view ends up partially
8188     * behind the camera (which is why the recommendation is to use a distance at
8189     * least as far as the size of the view, if the view is to be rotated.)</p>
8190     *
8191     * <p>The distance is expressed in "depth pixels." The default distance depends
8192     * on the screen density. For instance, on a medium density display, the
8193     * default distance is 1280. On a high density display, the default distance
8194     * is 1920.</p>
8195     *
8196     * <p>If you want to specify a distance that leads to visually consistent
8197     * results across various densities, use the following formula:</p>
8198     * <pre>
8199     * float scale = context.getResources().getDisplayMetrics().density;
8200     * view.setCameraDistance(distance * scale);
8201     * </pre>
8202     *
8203     * <p>The density scale factor of a high density display is 1.5,
8204     * and 1920 = 1280 * 1.5.</p>
8205     *
8206     * @param distance The distance in "depth pixels", if negative the opposite
8207     *        value is used
8208     *
8209     * @see #setRotationX(float)
8210     * @see #setRotationY(float)
8211     */
8212    public void setCameraDistance(float distance) {
8213        invalidateViewProperty(true, false);
8214
8215        ensureTransformationInfo();
8216        final float dpi = mResources.getDisplayMetrics().densityDpi;
8217        final TransformationInfo info = mTransformationInfo;
8218        if (info.mCamera == null) {
8219            info.mCamera = new Camera();
8220            info.matrix3D = new Matrix();
8221        }
8222
8223        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8224        info.mMatrixDirty = true;
8225
8226        invalidateViewProperty(false, false);
8227        if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8228            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8229        }
8230    }
8231
8232    /**
8233     * The degrees that the view is rotated around the pivot point.
8234     *
8235     * @see #setRotation(float)
8236     * @see #getPivotX()
8237     * @see #getPivotY()
8238     *
8239     * @return The degrees of rotation.
8240     */
8241    @ViewDebug.ExportedProperty(category = "drawing")
8242    public float getRotation() {
8243        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8244    }
8245
8246    /**
8247     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8248     * result in clockwise rotation.
8249     *
8250     * @param rotation The degrees of rotation.
8251     *
8252     * @see #getRotation()
8253     * @see #getPivotX()
8254     * @see #getPivotY()
8255     * @see #setRotationX(float)
8256     * @see #setRotationY(float)
8257     *
8258     * @attr ref android.R.styleable#View_rotation
8259     */
8260    public void setRotation(float rotation) {
8261        ensureTransformationInfo();
8262        final TransformationInfo info = mTransformationInfo;
8263        if (info.mRotation != rotation) {
8264            // Double-invalidation is necessary to capture view's old and new areas
8265            invalidateViewProperty(true, false);
8266            info.mRotation = rotation;
8267            info.mMatrixDirty = true;
8268            invalidateViewProperty(false, true);
8269            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8270                mDisplayList.setRotation(rotation);
8271            }
8272        }
8273    }
8274
8275    /**
8276     * The degrees that the view is rotated around the vertical axis through the pivot point.
8277     *
8278     * @see #getPivotX()
8279     * @see #getPivotY()
8280     * @see #setRotationY(float)
8281     *
8282     * @return The degrees of Y rotation.
8283     */
8284    @ViewDebug.ExportedProperty(category = "drawing")
8285    public float getRotationY() {
8286        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8287    }
8288
8289    /**
8290     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8291     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8292     * down the y axis.
8293     *
8294     * When rotating large views, it is recommended to adjust the camera distance
8295     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8296     *
8297     * @param rotationY The degrees of Y rotation.
8298     *
8299     * @see #getRotationY()
8300     * @see #getPivotX()
8301     * @see #getPivotY()
8302     * @see #setRotation(float)
8303     * @see #setRotationX(float)
8304     * @see #setCameraDistance(float)
8305     *
8306     * @attr ref android.R.styleable#View_rotationY
8307     */
8308    public void setRotationY(float rotationY) {
8309        ensureTransformationInfo();
8310        final TransformationInfo info = mTransformationInfo;
8311        if (info.mRotationY != rotationY) {
8312            invalidateViewProperty(true, false);
8313            info.mRotationY = rotationY;
8314            info.mMatrixDirty = true;
8315            invalidateViewProperty(false, true);
8316            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8317                mDisplayList.setRotationY(rotationY);
8318            }
8319        }
8320    }
8321
8322    /**
8323     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8324     *
8325     * @see #getPivotX()
8326     * @see #getPivotY()
8327     * @see #setRotationX(float)
8328     *
8329     * @return The degrees of X rotation.
8330     */
8331    @ViewDebug.ExportedProperty(category = "drawing")
8332    public float getRotationX() {
8333        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8334    }
8335
8336    /**
8337     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8338     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8339     * x axis.
8340     *
8341     * When rotating large views, it is recommended to adjust the camera distance
8342     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8343     *
8344     * @param rotationX The degrees of X rotation.
8345     *
8346     * @see #getRotationX()
8347     * @see #getPivotX()
8348     * @see #getPivotY()
8349     * @see #setRotation(float)
8350     * @see #setRotationY(float)
8351     * @see #setCameraDistance(float)
8352     *
8353     * @attr ref android.R.styleable#View_rotationX
8354     */
8355    public void setRotationX(float rotationX) {
8356        ensureTransformationInfo();
8357        final TransformationInfo info = mTransformationInfo;
8358        if (info.mRotationX != rotationX) {
8359            invalidateViewProperty(true, false);
8360            info.mRotationX = rotationX;
8361            info.mMatrixDirty = true;
8362            invalidateViewProperty(false, true);
8363            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8364                mDisplayList.setRotationX(rotationX);
8365            }
8366        }
8367    }
8368
8369    /**
8370     * The amount that the view is scaled in x around the pivot point, as a proportion of
8371     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8372     *
8373     * <p>By default, this is 1.0f.
8374     *
8375     * @see #getPivotX()
8376     * @see #getPivotY()
8377     * @return The scaling factor.
8378     */
8379    @ViewDebug.ExportedProperty(category = "drawing")
8380    public float getScaleX() {
8381        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8382    }
8383
8384    /**
8385     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8386     * the view's unscaled width. A value of 1 means that no scaling is applied.
8387     *
8388     * @param scaleX The scaling factor.
8389     * @see #getPivotX()
8390     * @see #getPivotY()
8391     *
8392     * @attr ref android.R.styleable#View_scaleX
8393     */
8394    public void setScaleX(float scaleX) {
8395        ensureTransformationInfo();
8396        final TransformationInfo info = mTransformationInfo;
8397        if (info.mScaleX != scaleX) {
8398            invalidateViewProperty(true, false);
8399            info.mScaleX = scaleX;
8400            info.mMatrixDirty = true;
8401            invalidateViewProperty(false, true);
8402            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8403                mDisplayList.setScaleX(scaleX);
8404            }
8405        }
8406    }
8407
8408    /**
8409     * The amount that the view is scaled in y around the pivot point, as a proportion of
8410     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8411     *
8412     * <p>By default, this is 1.0f.
8413     *
8414     * @see #getPivotX()
8415     * @see #getPivotY()
8416     * @return The scaling factor.
8417     */
8418    @ViewDebug.ExportedProperty(category = "drawing")
8419    public float getScaleY() {
8420        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8421    }
8422
8423    /**
8424     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8425     * the view's unscaled width. A value of 1 means that no scaling is applied.
8426     *
8427     * @param scaleY The scaling factor.
8428     * @see #getPivotX()
8429     * @see #getPivotY()
8430     *
8431     * @attr ref android.R.styleable#View_scaleY
8432     */
8433    public void setScaleY(float scaleY) {
8434        ensureTransformationInfo();
8435        final TransformationInfo info = mTransformationInfo;
8436        if (info.mScaleY != scaleY) {
8437            invalidateViewProperty(true, false);
8438            info.mScaleY = scaleY;
8439            info.mMatrixDirty = true;
8440            invalidateViewProperty(false, true);
8441            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8442                mDisplayList.setScaleY(scaleY);
8443            }
8444        }
8445    }
8446
8447    /**
8448     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8449     * and {@link #setScaleX(float) scaled}.
8450     *
8451     * @see #getRotation()
8452     * @see #getScaleX()
8453     * @see #getScaleY()
8454     * @see #getPivotY()
8455     * @return The x location of the pivot point.
8456     *
8457     * @attr ref android.R.styleable#View_transformPivotX
8458     */
8459    @ViewDebug.ExportedProperty(category = "drawing")
8460    public float getPivotX() {
8461        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8462    }
8463
8464    /**
8465     * Sets the x location of the point around which the view is
8466     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8467     * By default, the pivot point is centered on the object.
8468     * Setting this property disables this behavior and causes the view to use only the
8469     * explicitly set pivotX and pivotY values.
8470     *
8471     * @param pivotX The x location of the pivot point.
8472     * @see #getRotation()
8473     * @see #getScaleX()
8474     * @see #getScaleY()
8475     * @see #getPivotY()
8476     *
8477     * @attr ref android.R.styleable#View_transformPivotX
8478     */
8479    public void setPivotX(float pivotX) {
8480        ensureTransformationInfo();
8481        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8482        final TransformationInfo info = mTransformationInfo;
8483        if (info.mPivotX != pivotX) {
8484            invalidateViewProperty(true, false);
8485            info.mPivotX = pivotX;
8486            info.mMatrixDirty = true;
8487            invalidateViewProperty(false, true);
8488            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8489                mDisplayList.setPivotX(pivotX);
8490            }
8491        }
8492    }
8493
8494    /**
8495     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8496     * and {@link #setScaleY(float) scaled}.
8497     *
8498     * @see #getRotation()
8499     * @see #getScaleX()
8500     * @see #getScaleY()
8501     * @see #getPivotY()
8502     * @return The y location of the pivot point.
8503     *
8504     * @attr ref android.R.styleable#View_transformPivotY
8505     */
8506    @ViewDebug.ExportedProperty(category = "drawing")
8507    public float getPivotY() {
8508        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8509    }
8510
8511    /**
8512     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8513     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8514     * Setting this property disables this behavior and causes the view to use only the
8515     * explicitly set pivotX and pivotY values.
8516     *
8517     * @param pivotY The y location of the pivot point.
8518     * @see #getRotation()
8519     * @see #getScaleX()
8520     * @see #getScaleY()
8521     * @see #getPivotY()
8522     *
8523     * @attr ref android.R.styleable#View_transformPivotY
8524     */
8525    public void setPivotY(float pivotY) {
8526        ensureTransformationInfo();
8527        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8528        final TransformationInfo info = mTransformationInfo;
8529        if (info.mPivotY != pivotY) {
8530            invalidateViewProperty(true, false);
8531            info.mPivotY = pivotY;
8532            info.mMatrixDirty = true;
8533            invalidateViewProperty(false, true);
8534            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8535                mDisplayList.setPivotY(pivotY);
8536            }
8537        }
8538    }
8539
8540    /**
8541     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8542     * completely transparent and 1 means the view is completely opaque.
8543     *
8544     * <p>By default this is 1.0f.
8545     * @return The opacity of the view.
8546     */
8547    @ViewDebug.ExportedProperty(category = "drawing")
8548    public float getAlpha() {
8549        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8550    }
8551
8552    /**
8553     * Returns whether this View has content which overlaps. This function, intended to be
8554     * overridden by specific View types, is an optimization when alpha is set on a view. If
8555     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8556     * and then composited it into place, which can be expensive. If the view has no overlapping
8557     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8558     * An example of overlapping rendering is a TextView with a background image, such as a
8559     * Button. An example of non-overlapping rendering is a TextView with no background, or
8560     * an ImageView with only the foreground image. The default implementation returns true;
8561     * subclasses should override if they have cases which can be optimized.
8562     *
8563     * @return true if the content in this view might overlap, false otherwise.
8564     */
8565    public boolean hasOverlappingRendering() {
8566        return true;
8567    }
8568
8569    /**
8570     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8571     * completely transparent and 1 means the view is completely opaque.</p>
8572     *
8573     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8574     * responsible for applying the opacity itself. Otherwise, calling this method is
8575     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8576     * setting a hardware layer.</p>
8577     *
8578     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8579     * performance implications. It is generally best to use the alpha property sparingly and
8580     * transiently, as in the case of fading animations.</p>
8581     *
8582     * @param alpha The opacity of the view.
8583     *
8584     * @see #setLayerType(int, android.graphics.Paint)
8585     *
8586     * @attr ref android.R.styleable#View_alpha
8587     */
8588    public void setAlpha(float alpha) {
8589        ensureTransformationInfo();
8590        if (mTransformationInfo.mAlpha != alpha) {
8591            mTransformationInfo.mAlpha = alpha;
8592            if (onSetAlpha((int) (alpha * 255))) {
8593                mPrivateFlags |= ALPHA_SET;
8594                // subclass is handling alpha - don't optimize rendering cache invalidation
8595                invalidateParentCaches();
8596                invalidate(true);
8597            } else {
8598                mPrivateFlags &= ~ALPHA_SET;
8599                invalidateViewProperty(true, false);
8600                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8601                    mDisplayList.setAlpha(alpha);
8602                }
8603            }
8604        }
8605    }
8606
8607    /**
8608     * Faster version of setAlpha() which performs the same steps except there are
8609     * no calls to invalidate(). The caller of this function should perform proper invalidation
8610     * on the parent and this object. The return value indicates whether the subclass handles
8611     * alpha (the return value for onSetAlpha()).
8612     *
8613     * @param alpha The new value for the alpha property
8614     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8615     *         the new value for the alpha property is different from the old value
8616     */
8617    boolean setAlphaNoInvalidation(float alpha) {
8618        ensureTransformationInfo();
8619        if (mTransformationInfo.mAlpha != alpha) {
8620            mTransformationInfo.mAlpha = alpha;
8621            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8622            if (subclassHandlesAlpha) {
8623                mPrivateFlags |= ALPHA_SET;
8624                return true;
8625            } else {
8626                mPrivateFlags &= ~ALPHA_SET;
8627                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8628                    mDisplayList.setAlpha(alpha);
8629                }
8630            }
8631        }
8632        return false;
8633    }
8634
8635    /**
8636     * Top position of this view relative to its parent.
8637     *
8638     * @return The top of this view, in pixels.
8639     */
8640    @ViewDebug.CapturedViewProperty
8641    public final int getTop() {
8642        return mTop;
8643    }
8644
8645    /**
8646     * Sets the top position of this view relative to its parent. This method is meant to be called
8647     * by the layout system and should not generally be called otherwise, because the property
8648     * may be changed at any time by the layout.
8649     *
8650     * @param top The top of this view, in pixels.
8651     */
8652    public final void setTop(int top) {
8653        if (top != mTop) {
8654            updateMatrix();
8655            final boolean matrixIsIdentity = mTransformationInfo == null
8656                    || mTransformationInfo.mMatrixIsIdentity;
8657            if (matrixIsIdentity) {
8658                if (mAttachInfo != null) {
8659                    int minTop;
8660                    int yLoc;
8661                    if (top < mTop) {
8662                        minTop = top;
8663                        yLoc = top - mTop;
8664                    } else {
8665                        minTop = mTop;
8666                        yLoc = 0;
8667                    }
8668                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8669                }
8670            } else {
8671                // Double-invalidation is necessary to capture view's old and new areas
8672                invalidate(true);
8673            }
8674
8675            int width = mRight - mLeft;
8676            int oldHeight = mBottom - mTop;
8677
8678            mTop = top;
8679            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8680                mDisplayList.setTop(mTop);
8681            }
8682
8683            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8684
8685            if (!matrixIsIdentity) {
8686                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8687                    // A change in dimension means an auto-centered pivot point changes, too
8688                    mTransformationInfo.mMatrixDirty = true;
8689                }
8690                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8691                invalidate(true);
8692            }
8693            mBackgroundSizeChanged = true;
8694            invalidateParentIfNeeded();
8695        }
8696    }
8697
8698    /**
8699     * Bottom position of this view relative to its parent.
8700     *
8701     * @return The bottom of this view, in pixels.
8702     */
8703    @ViewDebug.CapturedViewProperty
8704    public final int getBottom() {
8705        return mBottom;
8706    }
8707
8708    /**
8709     * True if this view has changed since the last time being drawn.
8710     *
8711     * @return The dirty state of this view.
8712     */
8713    public boolean isDirty() {
8714        return (mPrivateFlags & DIRTY_MASK) != 0;
8715    }
8716
8717    /**
8718     * Sets the bottom position of this view relative to its parent. This method is meant to be
8719     * called by the layout system and should not generally be called otherwise, because the
8720     * property may be changed at any time by the layout.
8721     *
8722     * @param bottom The bottom of this view, in pixels.
8723     */
8724    public final void setBottom(int bottom) {
8725        if (bottom != mBottom) {
8726            updateMatrix();
8727            final boolean matrixIsIdentity = mTransformationInfo == null
8728                    || mTransformationInfo.mMatrixIsIdentity;
8729            if (matrixIsIdentity) {
8730                if (mAttachInfo != null) {
8731                    int maxBottom;
8732                    if (bottom < mBottom) {
8733                        maxBottom = mBottom;
8734                    } else {
8735                        maxBottom = bottom;
8736                    }
8737                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
8738                }
8739            } else {
8740                // Double-invalidation is necessary to capture view's old and new areas
8741                invalidate(true);
8742            }
8743
8744            int width = mRight - mLeft;
8745            int oldHeight = mBottom - mTop;
8746
8747            mBottom = bottom;
8748            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8749                mDisplayList.setBottom(mBottom);
8750            }
8751
8752            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8753
8754            if (!matrixIsIdentity) {
8755                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8756                    // A change in dimension means an auto-centered pivot point changes, too
8757                    mTransformationInfo.mMatrixDirty = true;
8758                }
8759                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8760                invalidate(true);
8761            }
8762            mBackgroundSizeChanged = true;
8763            invalidateParentIfNeeded();
8764        }
8765    }
8766
8767    /**
8768     * Left position of this view relative to its parent.
8769     *
8770     * @return The left edge of this view, in pixels.
8771     */
8772    @ViewDebug.CapturedViewProperty
8773    public final int getLeft() {
8774        return mLeft;
8775    }
8776
8777    /**
8778     * Sets the left position of this view relative to its parent. This method is meant to be called
8779     * by the layout system and should not generally be called otherwise, because the property
8780     * may be changed at any time by the layout.
8781     *
8782     * @param left The bottom of this view, in pixels.
8783     */
8784    public final void setLeft(int left) {
8785        if (left != mLeft) {
8786            updateMatrix();
8787            final boolean matrixIsIdentity = mTransformationInfo == null
8788                    || mTransformationInfo.mMatrixIsIdentity;
8789            if (matrixIsIdentity) {
8790                if (mAttachInfo != null) {
8791                    int minLeft;
8792                    int xLoc;
8793                    if (left < mLeft) {
8794                        minLeft = left;
8795                        xLoc = left - mLeft;
8796                    } else {
8797                        minLeft = mLeft;
8798                        xLoc = 0;
8799                    }
8800                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
8801                }
8802            } else {
8803                // Double-invalidation is necessary to capture view's old and new areas
8804                invalidate(true);
8805            }
8806
8807            int oldWidth = mRight - mLeft;
8808            int height = mBottom - mTop;
8809
8810            mLeft = left;
8811            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8812                mDisplayList.setLeft(left);
8813            }
8814
8815            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8816
8817            if (!matrixIsIdentity) {
8818                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8819                    // A change in dimension means an auto-centered pivot point changes, too
8820                    mTransformationInfo.mMatrixDirty = true;
8821                }
8822                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8823                invalidate(true);
8824            }
8825            mBackgroundSizeChanged = true;
8826            invalidateParentIfNeeded();
8827            if (USE_DISPLAY_LIST_PROPERTIES) {
8828
8829            }
8830        }
8831    }
8832
8833    /**
8834     * Right position of this view relative to its parent.
8835     *
8836     * @return The right edge of this view, in pixels.
8837     */
8838    @ViewDebug.CapturedViewProperty
8839    public final int getRight() {
8840        return mRight;
8841    }
8842
8843    /**
8844     * Sets the right position of this view relative to its parent. This method is meant to be called
8845     * by the layout system and should not generally be called otherwise, because the property
8846     * may be changed at any time by the layout.
8847     *
8848     * @param right The bottom of this view, in pixels.
8849     */
8850    public final void setRight(int right) {
8851        if (right != mRight) {
8852            updateMatrix();
8853            final boolean matrixIsIdentity = mTransformationInfo == null
8854                    || mTransformationInfo.mMatrixIsIdentity;
8855            if (matrixIsIdentity) {
8856                if (mAttachInfo != null) {
8857                    int maxRight;
8858                    if (right < mRight) {
8859                        maxRight = mRight;
8860                    } else {
8861                        maxRight = right;
8862                    }
8863                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
8864                }
8865            } else {
8866                // Double-invalidation is necessary to capture view's old and new areas
8867                invalidate(true);
8868            }
8869
8870            int oldWidth = mRight - mLeft;
8871            int height = mBottom - mTop;
8872
8873            mRight = right;
8874            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8875                mDisplayList.setRight(mRight);
8876            }
8877
8878            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8879
8880            if (!matrixIsIdentity) {
8881                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8882                    // A change in dimension means an auto-centered pivot point changes, too
8883                    mTransformationInfo.mMatrixDirty = true;
8884                }
8885                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8886                invalidate(true);
8887            }
8888            mBackgroundSizeChanged = true;
8889            invalidateParentIfNeeded();
8890        }
8891    }
8892
8893    /**
8894     * The visual x position of this view, in pixels. This is equivalent to the
8895     * {@link #setTranslationX(float) translationX} property plus the current
8896     * {@link #getLeft() left} property.
8897     *
8898     * @return The visual x position of this view, in pixels.
8899     */
8900    @ViewDebug.ExportedProperty(category = "drawing")
8901    public float getX() {
8902        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8903    }
8904
8905    /**
8906     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8907     * {@link #setTranslationX(float) translationX} property to be the difference between
8908     * the x value passed in and the current {@link #getLeft() left} property.
8909     *
8910     * @param x The visual x position of this view, in pixels.
8911     */
8912    public void setX(float x) {
8913        setTranslationX(x - mLeft);
8914    }
8915
8916    /**
8917     * The visual y position of this view, in pixels. This is equivalent to the
8918     * {@link #setTranslationY(float) translationY} property plus the current
8919     * {@link #getTop() top} property.
8920     *
8921     * @return The visual y position of this view, in pixels.
8922     */
8923    @ViewDebug.ExportedProperty(category = "drawing")
8924    public float getY() {
8925        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8926    }
8927
8928    /**
8929     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
8930     * {@link #setTranslationY(float) translationY} property to be the difference between
8931     * the y value passed in and the current {@link #getTop() top} property.
8932     *
8933     * @param y The visual y position of this view, in pixels.
8934     */
8935    public void setY(float y) {
8936        setTranslationY(y - mTop);
8937    }
8938
8939
8940    /**
8941     * The horizontal location of this view relative to its {@link #getLeft() left} position.
8942     * This position is post-layout, in addition to wherever the object's
8943     * layout placed it.
8944     *
8945     * @return The horizontal position of this view relative to its left position, in pixels.
8946     */
8947    @ViewDebug.ExportedProperty(category = "drawing")
8948    public float getTranslationX() {
8949        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
8950    }
8951
8952    /**
8953     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
8954     * This effectively positions the object post-layout, in addition to wherever the object's
8955     * layout placed it.
8956     *
8957     * @param translationX The horizontal position of this view relative to its left position,
8958     * in pixels.
8959     *
8960     * @attr ref android.R.styleable#View_translationX
8961     */
8962    public void setTranslationX(float translationX) {
8963        ensureTransformationInfo();
8964        final TransformationInfo info = mTransformationInfo;
8965        if (info.mTranslationX != translationX) {
8966            // Double-invalidation is necessary to capture view's old and new areas
8967            invalidateViewProperty(true, false);
8968            info.mTranslationX = translationX;
8969            info.mMatrixDirty = true;
8970            invalidateViewProperty(false, true);
8971            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8972                mDisplayList.setTranslationX(translationX);
8973            }
8974        }
8975    }
8976
8977    /**
8978     * The horizontal location of this view relative to its {@link #getTop() top} position.
8979     * This position is post-layout, in addition to wherever the object's
8980     * layout placed it.
8981     *
8982     * @return The vertical position of this view relative to its top position,
8983     * in pixels.
8984     */
8985    @ViewDebug.ExportedProperty(category = "drawing")
8986    public float getTranslationY() {
8987        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
8988    }
8989
8990    /**
8991     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
8992     * This effectively positions the object post-layout, in addition to wherever the object's
8993     * layout placed it.
8994     *
8995     * @param translationY The vertical position of this view relative to its top position,
8996     * in pixels.
8997     *
8998     * @attr ref android.R.styleable#View_translationY
8999     */
9000    public void setTranslationY(float translationY) {
9001        ensureTransformationInfo();
9002        final TransformationInfo info = mTransformationInfo;
9003        if (info.mTranslationY != translationY) {
9004            invalidateViewProperty(true, false);
9005            info.mTranslationY = translationY;
9006            info.mMatrixDirty = true;
9007            invalidateViewProperty(false, true);
9008            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
9009                mDisplayList.setTranslationY(translationY);
9010            }
9011        }
9012    }
9013
9014    /**
9015     * Hit rectangle in parent's coordinates
9016     *
9017     * @param outRect The hit rectangle of the view.
9018     */
9019    public void getHitRect(Rect outRect) {
9020        updateMatrix();
9021        final TransformationInfo info = mTransformationInfo;
9022        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9023            outRect.set(mLeft, mTop, mRight, mBottom);
9024        } else {
9025            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9026            tmpRect.set(-info.mPivotX, -info.mPivotY,
9027                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9028            info.mMatrix.mapRect(tmpRect);
9029            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9030                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9031        }
9032    }
9033
9034    /**
9035     * Determines whether the given point, in local coordinates is inside the view.
9036     */
9037    /*package*/ final boolean pointInView(float localX, float localY) {
9038        return localX >= 0 && localX < (mRight - mLeft)
9039                && localY >= 0 && localY < (mBottom - mTop);
9040    }
9041
9042    /**
9043     * Utility method to determine whether the given point, in local coordinates,
9044     * is inside the view, where the area of the view is expanded by the slop factor.
9045     * This method is called while processing touch-move events to determine if the event
9046     * is still within the view.
9047     */
9048    private boolean pointInView(float localX, float localY, float slop) {
9049        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9050                localY < ((mBottom - mTop) + slop);
9051    }
9052
9053    /**
9054     * When a view has focus and the user navigates away from it, the next view is searched for
9055     * starting from the rectangle filled in by this method.
9056     *
9057     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9058     * of the view.  However, if your view maintains some idea of internal selection,
9059     * such as a cursor, or a selected row or column, you should override this method and
9060     * fill in a more specific rectangle.
9061     *
9062     * @param r The rectangle to fill in, in this view's coordinates.
9063     */
9064    public void getFocusedRect(Rect r) {
9065        getDrawingRect(r);
9066    }
9067
9068    /**
9069     * If some part of this view is not clipped by any of its parents, then
9070     * return that area in r in global (root) coordinates. To convert r to local
9071     * coordinates (without taking possible View rotations into account), offset
9072     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9073     * If the view is completely clipped or translated out, return false.
9074     *
9075     * @param r If true is returned, r holds the global coordinates of the
9076     *        visible portion of this view.
9077     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9078     *        between this view and its root. globalOffet may be null.
9079     * @return true if r is non-empty (i.e. part of the view is visible at the
9080     *         root level.
9081     */
9082    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9083        int width = mRight - mLeft;
9084        int height = mBottom - mTop;
9085        if (width > 0 && height > 0) {
9086            r.set(0, 0, width, height);
9087            if (globalOffset != null) {
9088                globalOffset.set(-mScrollX, -mScrollY);
9089            }
9090            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9091        }
9092        return false;
9093    }
9094
9095    public final boolean getGlobalVisibleRect(Rect r) {
9096        return getGlobalVisibleRect(r, null);
9097    }
9098
9099    public final boolean getLocalVisibleRect(Rect r) {
9100        Point offset = new Point();
9101        if (getGlobalVisibleRect(r, offset)) {
9102            r.offset(-offset.x, -offset.y); // make r local
9103            return true;
9104        }
9105        return false;
9106    }
9107
9108    /**
9109     * Offset this view's vertical location by the specified number of pixels.
9110     *
9111     * @param offset the number of pixels to offset the view by
9112     */
9113    public void offsetTopAndBottom(int offset) {
9114        if (offset != 0) {
9115            updateMatrix();
9116            final boolean matrixIsIdentity = mTransformationInfo == null
9117                    || mTransformationInfo.mMatrixIsIdentity;
9118            if (matrixIsIdentity) {
9119                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
9120                    invalidateViewProperty(false, false);
9121                } else {
9122                    final ViewParent p = mParent;
9123                    if (p != null && mAttachInfo != null) {
9124                        final Rect r = mAttachInfo.mTmpInvalRect;
9125                        int minTop;
9126                        int maxBottom;
9127                        int yLoc;
9128                        if (offset < 0) {
9129                            minTop = mTop + offset;
9130                            maxBottom = mBottom;
9131                            yLoc = offset;
9132                        } else {
9133                            minTop = mTop;
9134                            maxBottom = mBottom + offset;
9135                            yLoc = 0;
9136                        }
9137                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9138                        p.invalidateChild(this, r);
9139                    }
9140                }
9141            } else {
9142                invalidateViewProperty(false, false);
9143            }
9144
9145            mTop += offset;
9146            mBottom += offset;
9147            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
9148                mDisplayList.offsetTopBottom(offset);
9149                invalidateViewProperty(false, false);
9150            } else {
9151                if (!matrixIsIdentity) {
9152                    invalidateViewProperty(false, true);
9153                }
9154                invalidateParentIfNeeded();
9155            }
9156        }
9157    }
9158
9159    /**
9160     * Offset this view's horizontal location by the specified amount of pixels.
9161     *
9162     * @param offset the numer of pixels to offset the view by
9163     */
9164    public void offsetLeftAndRight(int offset) {
9165        if (offset != 0) {
9166            updateMatrix();
9167            final boolean matrixIsIdentity = mTransformationInfo == null
9168                    || mTransformationInfo.mMatrixIsIdentity;
9169            if (matrixIsIdentity) {
9170                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
9171                    invalidateViewProperty(false, false);
9172                } else {
9173                    final ViewParent p = mParent;
9174                    if (p != null && mAttachInfo != null) {
9175                        final Rect r = mAttachInfo.mTmpInvalRect;
9176                        int minLeft;
9177                        int maxRight;
9178                        if (offset < 0) {
9179                            minLeft = mLeft + offset;
9180                            maxRight = mRight;
9181                        } else {
9182                            minLeft = mLeft;
9183                            maxRight = mRight + offset;
9184                        }
9185                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9186                        p.invalidateChild(this, r);
9187                    }
9188                }
9189            } else {
9190                invalidateViewProperty(false, false);
9191            }
9192
9193            mLeft += offset;
9194            mRight += offset;
9195            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
9196                mDisplayList.offsetLeftRight(offset);
9197                invalidateViewProperty(false, false);
9198            } else {
9199                if (!matrixIsIdentity) {
9200                    invalidateViewProperty(false, true);
9201                }
9202                invalidateParentIfNeeded();
9203            }
9204        }
9205    }
9206
9207    /**
9208     * Get the LayoutParams associated with this view. All views should have
9209     * layout parameters. These supply parameters to the <i>parent</i> of this
9210     * view specifying how it should be arranged. There are many subclasses of
9211     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9212     * of ViewGroup that are responsible for arranging their children.
9213     *
9214     * This method may return null if this View is not attached to a parent
9215     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9216     * was not invoked successfully. When a View is attached to a parent
9217     * ViewGroup, this method must not return null.
9218     *
9219     * @return The LayoutParams associated with this view, or null if no
9220     *         parameters have been set yet
9221     */
9222    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9223    public ViewGroup.LayoutParams getLayoutParams() {
9224        return mLayoutParams;
9225    }
9226
9227    /**
9228     * Set the layout parameters associated with this view. These supply
9229     * parameters to the <i>parent</i> of this view specifying how it should be
9230     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9231     * correspond to the different subclasses of ViewGroup that are responsible
9232     * for arranging their children.
9233     *
9234     * @param params The layout parameters for this view, cannot be null
9235     */
9236    public void setLayoutParams(ViewGroup.LayoutParams params) {
9237        if (params == null) {
9238            throw new NullPointerException("Layout parameters cannot be null");
9239        }
9240        mLayoutParams = params;
9241        if (mParent instanceof ViewGroup) {
9242            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9243        }
9244        requestLayout();
9245    }
9246
9247    /**
9248     * Set the scrolled position of your view. This will cause a call to
9249     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9250     * invalidated.
9251     * @param x the x position to scroll to
9252     * @param y the y position to scroll to
9253     */
9254    public void scrollTo(int x, int y) {
9255        if (mScrollX != x || mScrollY != y) {
9256            int oldX = mScrollX;
9257            int oldY = mScrollY;
9258            mScrollX = x;
9259            mScrollY = y;
9260            invalidateParentCaches();
9261            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9262            if (!awakenScrollBars()) {
9263                postInvalidateOnAnimation();
9264            }
9265        }
9266    }
9267
9268    /**
9269     * Move the scrolled position of your view. This will cause a call to
9270     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9271     * invalidated.
9272     * @param x the amount of pixels to scroll by horizontally
9273     * @param y the amount of pixels to scroll by vertically
9274     */
9275    public void scrollBy(int x, int y) {
9276        scrollTo(mScrollX + x, mScrollY + y);
9277    }
9278
9279    /**
9280     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9281     * animation to fade the scrollbars out after a default delay. If a subclass
9282     * provides animated scrolling, the start delay should equal the duration
9283     * of the scrolling animation.</p>
9284     *
9285     * <p>The animation starts only if at least one of the scrollbars is
9286     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9287     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9288     * this method returns true, and false otherwise. If the animation is
9289     * started, this method calls {@link #invalidate()}; in that case the
9290     * caller should not call {@link #invalidate()}.</p>
9291     *
9292     * <p>This method should be invoked every time a subclass directly updates
9293     * the scroll parameters.</p>
9294     *
9295     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9296     * and {@link #scrollTo(int, int)}.</p>
9297     *
9298     * @return true if the animation is played, false otherwise
9299     *
9300     * @see #awakenScrollBars(int)
9301     * @see #scrollBy(int, int)
9302     * @see #scrollTo(int, int)
9303     * @see #isHorizontalScrollBarEnabled()
9304     * @see #isVerticalScrollBarEnabled()
9305     * @see #setHorizontalScrollBarEnabled(boolean)
9306     * @see #setVerticalScrollBarEnabled(boolean)
9307     */
9308    protected boolean awakenScrollBars() {
9309        return mScrollCache != null &&
9310                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9311    }
9312
9313    /**
9314     * Trigger the scrollbars to draw.
9315     * This method differs from awakenScrollBars() only in its default duration.
9316     * initialAwakenScrollBars() will show the scroll bars for longer than
9317     * usual to give the user more of a chance to notice them.
9318     *
9319     * @return true if the animation is played, false otherwise.
9320     */
9321    private boolean initialAwakenScrollBars() {
9322        return mScrollCache != null &&
9323                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9324    }
9325
9326    /**
9327     * <p>
9328     * Trigger the scrollbars to draw. When invoked this method starts an
9329     * animation to fade the scrollbars out after a fixed delay. If a subclass
9330     * provides animated scrolling, the start delay should equal the duration of
9331     * the scrolling animation.
9332     * </p>
9333     *
9334     * <p>
9335     * The animation starts only if at least one of the scrollbars is enabled,
9336     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9337     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9338     * this method returns true, and false otherwise. If the animation is
9339     * started, this method calls {@link #invalidate()}; in that case the caller
9340     * should not call {@link #invalidate()}.
9341     * </p>
9342     *
9343     * <p>
9344     * This method should be invoked everytime a subclass directly updates the
9345     * scroll parameters.
9346     * </p>
9347     *
9348     * @param startDelay the delay, in milliseconds, after which the animation
9349     *        should start; when the delay is 0, the animation starts
9350     *        immediately
9351     * @return true if the animation is played, false otherwise
9352     *
9353     * @see #scrollBy(int, int)
9354     * @see #scrollTo(int, int)
9355     * @see #isHorizontalScrollBarEnabled()
9356     * @see #isVerticalScrollBarEnabled()
9357     * @see #setHorizontalScrollBarEnabled(boolean)
9358     * @see #setVerticalScrollBarEnabled(boolean)
9359     */
9360    protected boolean awakenScrollBars(int startDelay) {
9361        return awakenScrollBars(startDelay, true);
9362    }
9363
9364    /**
9365     * <p>
9366     * Trigger the scrollbars to draw. When invoked this method starts an
9367     * animation to fade the scrollbars out after a fixed delay. If a subclass
9368     * provides animated scrolling, the start delay should equal the duration of
9369     * the scrolling animation.
9370     * </p>
9371     *
9372     * <p>
9373     * The animation starts only if at least one of the scrollbars is enabled,
9374     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9375     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9376     * this method returns true, and false otherwise. If the animation is
9377     * started, this method calls {@link #invalidate()} if the invalidate parameter
9378     * is set to true; in that case the caller
9379     * should not call {@link #invalidate()}.
9380     * </p>
9381     *
9382     * <p>
9383     * This method should be invoked everytime a subclass directly updates the
9384     * scroll parameters.
9385     * </p>
9386     *
9387     * @param startDelay the delay, in milliseconds, after which the animation
9388     *        should start; when the delay is 0, the animation starts
9389     *        immediately
9390     *
9391     * @param invalidate Wheter this method should call invalidate
9392     *
9393     * @return true if the animation is played, false otherwise
9394     *
9395     * @see #scrollBy(int, int)
9396     * @see #scrollTo(int, int)
9397     * @see #isHorizontalScrollBarEnabled()
9398     * @see #isVerticalScrollBarEnabled()
9399     * @see #setHorizontalScrollBarEnabled(boolean)
9400     * @see #setVerticalScrollBarEnabled(boolean)
9401     */
9402    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9403        final ScrollabilityCache scrollCache = mScrollCache;
9404
9405        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9406            return false;
9407        }
9408
9409        if (scrollCache.scrollBar == null) {
9410            scrollCache.scrollBar = new ScrollBarDrawable();
9411        }
9412
9413        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9414
9415            if (invalidate) {
9416                // Invalidate to show the scrollbars
9417                postInvalidateOnAnimation();
9418            }
9419
9420            if (scrollCache.state == ScrollabilityCache.OFF) {
9421                // FIXME: this is copied from WindowManagerService.
9422                // We should get this value from the system when it
9423                // is possible to do so.
9424                final int KEY_REPEAT_FIRST_DELAY = 750;
9425                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9426            }
9427
9428            // Tell mScrollCache when we should start fading. This may
9429            // extend the fade start time if one was already scheduled
9430            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9431            scrollCache.fadeStartTime = fadeStartTime;
9432            scrollCache.state = ScrollabilityCache.ON;
9433
9434            // Schedule our fader to run, unscheduling any old ones first
9435            if (mAttachInfo != null) {
9436                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9437                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9438            }
9439
9440            return true;
9441        }
9442
9443        return false;
9444    }
9445
9446    /**
9447     * Do not invalidate views which are not visible and which are not running an animation. They
9448     * will not get drawn and they should not set dirty flags as if they will be drawn
9449     */
9450    private boolean skipInvalidate() {
9451        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9452                (!(mParent instanceof ViewGroup) ||
9453                        !((ViewGroup) mParent).isViewTransitioning(this));
9454    }
9455    /**
9456     * Mark the area defined by dirty as needing to be drawn. If the view is
9457     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9458     * in the future. This must be called from a UI thread. To call from a non-UI
9459     * thread, call {@link #postInvalidate()}.
9460     *
9461     * WARNING: This method is destructive to dirty.
9462     * @param dirty the rectangle representing the bounds of the dirty region
9463     */
9464    public void invalidate(Rect dirty) {
9465        if (ViewDebug.TRACE_HIERARCHY) {
9466            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9467        }
9468
9469        if (skipInvalidate()) {
9470            return;
9471        }
9472        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9473                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9474                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9475            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9476            mPrivateFlags |= INVALIDATED;
9477            mPrivateFlags |= DIRTY;
9478            final ViewParent p = mParent;
9479            final AttachInfo ai = mAttachInfo;
9480            //noinspection PointlessBooleanExpression,ConstantConditions
9481            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9482                if (p != null && ai != null && ai.mHardwareAccelerated) {
9483                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9484                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9485                    p.invalidateChild(this, null);
9486                    return;
9487                }
9488            }
9489            if (p != null && ai != null) {
9490                final int scrollX = mScrollX;
9491                final int scrollY = mScrollY;
9492                final Rect r = ai.mTmpInvalRect;
9493                r.set(dirty.left - scrollX, dirty.top - scrollY,
9494                        dirty.right - scrollX, dirty.bottom - scrollY);
9495                mParent.invalidateChild(this, r);
9496            }
9497        }
9498    }
9499
9500    /**
9501     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9502     * The coordinates of the dirty rect are relative to the view.
9503     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9504     * will be called at some point in the future. This must be called from
9505     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9506     * @param l the left position of the dirty region
9507     * @param t the top position of the dirty region
9508     * @param r the right position of the dirty region
9509     * @param b the bottom position of the dirty region
9510     */
9511    public void invalidate(int l, int t, int r, int b) {
9512        if (ViewDebug.TRACE_HIERARCHY) {
9513            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9514        }
9515
9516        if (skipInvalidate()) {
9517            return;
9518        }
9519        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9520                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9521                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9522            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9523            mPrivateFlags |= INVALIDATED;
9524            mPrivateFlags |= DIRTY;
9525            final ViewParent p = mParent;
9526            final AttachInfo ai = mAttachInfo;
9527            //noinspection PointlessBooleanExpression,ConstantConditions
9528            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9529                if (p != null && ai != null && ai.mHardwareAccelerated) {
9530                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9531                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9532                    p.invalidateChild(this, null);
9533                    return;
9534                }
9535            }
9536            if (p != null && ai != null && l < r && t < b) {
9537                final int scrollX = mScrollX;
9538                final int scrollY = mScrollY;
9539                final Rect tmpr = ai.mTmpInvalRect;
9540                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9541                p.invalidateChild(this, tmpr);
9542            }
9543        }
9544    }
9545
9546    /**
9547     * Invalidate the whole view. If the view is visible,
9548     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9549     * the future. This must be called from a UI thread. To call from a non-UI thread,
9550     * call {@link #postInvalidate()}.
9551     */
9552    public void invalidate() {
9553        invalidate(true);
9554    }
9555
9556    /**
9557     * This is where the invalidate() work actually happens. A full invalidate()
9558     * causes the drawing cache to be invalidated, but this function can be called with
9559     * invalidateCache set to false to skip that invalidation step for cases that do not
9560     * need it (for example, a component that remains at the same dimensions with the same
9561     * content).
9562     *
9563     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9564     * well. This is usually true for a full invalidate, but may be set to false if the
9565     * View's contents or dimensions have not changed.
9566     */
9567    void invalidate(boolean invalidateCache) {
9568        if (ViewDebug.TRACE_HIERARCHY) {
9569            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9570        }
9571
9572        if (skipInvalidate()) {
9573            return;
9574        }
9575        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9576                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9577                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9578            mLastIsOpaque = isOpaque();
9579            mPrivateFlags &= ~DRAWN;
9580            mPrivateFlags |= DIRTY;
9581            if (invalidateCache) {
9582                mPrivateFlags |= INVALIDATED;
9583                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9584            }
9585            final AttachInfo ai = mAttachInfo;
9586            final ViewParent p = mParent;
9587            //noinspection PointlessBooleanExpression,ConstantConditions
9588            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9589                if (p != null && ai != null && ai.mHardwareAccelerated) {
9590                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9591                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9592                    p.invalidateChild(this, null);
9593                    return;
9594                }
9595            }
9596
9597            if (p != null && ai != null) {
9598                final Rect r = ai.mTmpInvalRect;
9599                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9600                // Don't call invalidate -- we don't want to internally scroll
9601                // our own bounds
9602                p.invalidateChild(this, r);
9603            }
9604        }
9605    }
9606
9607    /**
9608     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9609     * set any flags or handle all of the cases handled by the default invalidation methods.
9610     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9611     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9612     * walk up the hierarchy, transforming the dirty rect as necessary.
9613     *
9614     * The method also handles normal invalidation logic if display list properties are not
9615     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9616     * backup approach, to handle these cases used in the various property-setting methods.
9617     *
9618     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9619     * are not being used in this view
9620     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9621     * list properties are not being used in this view
9622     */
9623    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9624        if (!USE_DISPLAY_LIST_PROPERTIES || mDisplayList == null ||
9625                (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9626            if (invalidateParent) {
9627                invalidateParentCaches();
9628            }
9629            if (forceRedraw) {
9630                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9631            }
9632            invalidate(false);
9633        } else {
9634            final AttachInfo ai = mAttachInfo;
9635            final ViewParent p = mParent;
9636            if (p != null && ai != null) {
9637                final Rect r = ai.mTmpInvalRect;
9638                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9639                if (mParent instanceof ViewGroup) {
9640                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9641                } else {
9642                    mParent.invalidateChild(this, r);
9643                }
9644            }
9645        }
9646    }
9647
9648    /**
9649     * Utility method to transform a given Rect by the current matrix of this view.
9650     */
9651    void transformRect(final Rect rect) {
9652        if (!getMatrix().isIdentity()) {
9653            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9654            boundingRect.set(rect);
9655            getMatrix().mapRect(boundingRect);
9656            rect.set((int) (boundingRect.left - 0.5f),
9657                    (int) (boundingRect.top - 0.5f),
9658                    (int) (boundingRect.right + 0.5f),
9659                    (int) (boundingRect.bottom + 0.5f));
9660        }
9661    }
9662
9663    /**
9664     * Used to indicate that the parent of this view should clear its caches. This functionality
9665     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9666     * which is necessary when various parent-managed properties of the view change, such as
9667     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9668     * clears the parent caches and does not causes an invalidate event.
9669     *
9670     * @hide
9671     */
9672    protected void invalidateParentCaches() {
9673        if (mParent instanceof View) {
9674            ((View) mParent).mPrivateFlags |= INVALIDATED;
9675        }
9676    }
9677
9678    /**
9679     * Used to indicate that the parent of this view should be invalidated. This functionality
9680     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9681     * which is necessary when various parent-managed properties of the view change, such as
9682     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9683     * an invalidation event to the parent.
9684     *
9685     * @hide
9686     */
9687    protected void invalidateParentIfNeeded() {
9688        if (isHardwareAccelerated() && mParent instanceof View) {
9689            ((View) mParent).invalidate(true);
9690        }
9691    }
9692
9693    /**
9694     * Indicates whether this View is opaque. An opaque View guarantees that it will
9695     * draw all the pixels overlapping its bounds using a fully opaque color.
9696     *
9697     * Subclasses of View should override this method whenever possible to indicate
9698     * whether an instance is opaque. Opaque Views are treated in a special way by
9699     * the View hierarchy, possibly allowing it to perform optimizations during
9700     * invalidate/draw passes.
9701     *
9702     * @return True if this View is guaranteed to be fully opaque, false otherwise.
9703     */
9704    @ViewDebug.ExportedProperty(category = "drawing")
9705    public boolean isOpaque() {
9706        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
9707                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
9708                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
9709    }
9710
9711    /**
9712     * @hide
9713     */
9714    protected void computeOpaqueFlags() {
9715        // Opaque if:
9716        //   - Has a background
9717        //   - Background is opaque
9718        //   - Doesn't have scrollbars or scrollbars are inside overlay
9719
9720        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
9721            mPrivateFlags |= OPAQUE_BACKGROUND;
9722        } else {
9723            mPrivateFlags &= ~OPAQUE_BACKGROUND;
9724        }
9725
9726        final int flags = mViewFlags;
9727        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
9728                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
9729            mPrivateFlags |= OPAQUE_SCROLLBARS;
9730        } else {
9731            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
9732        }
9733    }
9734
9735    /**
9736     * @hide
9737     */
9738    protected boolean hasOpaqueScrollbars() {
9739        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
9740    }
9741
9742    /**
9743     * @return A handler associated with the thread running the View. This
9744     * handler can be used to pump events in the UI events queue.
9745     */
9746    public Handler getHandler() {
9747        if (mAttachInfo != null) {
9748            return mAttachInfo.mHandler;
9749        }
9750        return null;
9751    }
9752
9753    /**
9754     * Gets the view root associated with the View.
9755     * @return The view root, or null if none.
9756     * @hide
9757     */
9758    public ViewRootImpl getViewRootImpl() {
9759        if (mAttachInfo != null) {
9760            return mAttachInfo.mViewRootImpl;
9761        }
9762        return null;
9763    }
9764
9765    /**
9766     * <p>Causes the Runnable to be added to the message queue.
9767     * The runnable will be run on the user interface thread.</p>
9768     *
9769     * <p>This method can be invoked from outside of the UI thread
9770     * only when this View is attached to a window.</p>
9771     *
9772     * @param action The Runnable that will be executed.
9773     *
9774     * @return Returns true if the Runnable was successfully placed in to the
9775     *         message queue.  Returns false on failure, usually because the
9776     *         looper processing the message queue is exiting.
9777     *
9778     * @see #postDelayed
9779     * @see #removeCallbacks
9780     */
9781    public boolean post(Runnable action) {
9782        final AttachInfo attachInfo = mAttachInfo;
9783        if (attachInfo != null) {
9784            return attachInfo.mHandler.post(action);
9785        }
9786        // Assume that post will succeed later
9787        ViewRootImpl.getRunQueue().post(action);
9788        return true;
9789    }
9790
9791    /**
9792     * <p>Causes the Runnable to be added to the message queue, to be run
9793     * after the specified amount of time elapses.
9794     * The runnable will be run on the user interface thread.</p>
9795     *
9796     * <p>This method can be invoked from outside of the UI thread
9797     * only when this View is attached to a window.</p>
9798     *
9799     * @param action The Runnable that will be executed.
9800     * @param delayMillis The delay (in milliseconds) until the Runnable
9801     *        will be executed.
9802     *
9803     * @return true if the Runnable was successfully placed in to the
9804     *         message queue.  Returns false on failure, usually because the
9805     *         looper processing the message queue is exiting.  Note that a
9806     *         result of true does not mean the Runnable will be processed --
9807     *         if the looper is quit before the delivery time of the message
9808     *         occurs then the message will be dropped.
9809     *
9810     * @see #post
9811     * @see #removeCallbacks
9812     */
9813    public boolean postDelayed(Runnable action, long delayMillis) {
9814        final AttachInfo attachInfo = mAttachInfo;
9815        if (attachInfo != null) {
9816            return attachInfo.mHandler.postDelayed(action, delayMillis);
9817        }
9818        // Assume that post will succeed later
9819        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9820        return true;
9821    }
9822
9823    /**
9824     * <p>Causes the Runnable to execute on the next animation time step.
9825     * The runnable will be run on the user interface thread.</p>
9826     *
9827     * <p>This method can be invoked from outside of the UI thread
9828     * only when this View is attached to a window.</p>
9829     *
9830     * @param action The Runnable that will be executed.
9831     *
9832     * @see #postOnAnimationDelayed
9833     * @see #removeCallbacks
9834     */
9835    public void postOnAnimation(Runnable action) {
9836        final AttachInfo attachInfo = mAttachInfo;
9837        if (attachInfo != null) {
9838            attachInfo.mViewRootImpl.mChoreographer.postCallback(
9839                    Choreographer.CALLBACK_ANIMATION, action, null);
9840        } else {
9841            // Assume that post will succeed later
9842            ViewRootImpl.getRunQueue().post(action);
9843        }
9844    }
9845
9846    /**
9847     * <p>Causes the Runnable to execute on the next animation time step,
9848     * after the specified amount of time elapses.
9849     * The runnable will be run on the user interface thread.</p>
9850     *
9851     * <p>This method can be invoked from outside of the UI thread
9852     * only when this View is attached to a window.</p>
9853     *
9854     * @param action The Runnable that will be executed.
9855     * @param delayMillis The delay (in milliseconds) until the Runnable
9856     *        will be executed.
9857     *
9858     * @see #postOnAnimation
9859     * @see #removeCallbacks
9860     */
9861    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
9862        final AttachInfo attachInfo = mAttachInfo;
9863        if (attachInfo != null) {
9864            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
9865                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
9866        } else {
9867            // Assume that post will succeed later
9868            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9869        }
9870    }
9871
9872    /**
9873     * <p>Removes the specified Runnable from the message queue.</p>
9874     *
9875     * <p>This method can be invoked from outside of the UI thread
9876     * only when this View is attached to a window.</p>
9877     *
9878     * @param action The Runnable to remove from the message handling queue
9879     *
9880     * @return true if this view could ask the Handler to remove the Runnable,
9881     *         false otherwise. When the returned value is true, the Runnable
9882     *         may or may not have been actually removed from the message queue
9883     *         (for instance, if the Runnable was not in the queue already.)
9884     *
9885     * @see #post
9886     * @see #postDelayed
9887     * @see #postOnAnimation
9888     * @see #postOnAnimationDelayed
9889     */
9890    public boolean removeCallbacks(Runnable action) {
9891        if (action != null) {
9892            final AttachInfo attachInfo = mAttachInfo;
9893            if (attachInfo != null) {
9894                attachInfo.mHandler.removeCallbacks(action);
9895                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
9896                        Choreographer.CALLBACK_ANIMATION, action, null);
9897            } else {
9898                // Assume that post will succeed later
9899                ViewRootImpl.getRunQueue().removeCallbacks(action);
9900            }
9901        }
9902        return true;
9903    }
9904
9905    /**
9906     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
9907     * Use this to invalidate the View from a non-UI thread.</p>
9908     *
9909     * <p>This method can be invoked from outside of the UI thread
9910     * only when this View is attached to a window.</p>
9911     *
9912     * @see #invalidate()
9913     * @see #postInvalidateDelayed(long)
9914     */
9915    public void postInvalidate() {
9916        postInvalidateDelayed(0);
9917    }
9918
9919    /**
9920     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9921     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
9922     *
9923     * <p>This method can be invoked from outside of the UI thread
9924     * only when this View is attached to a window.</p>
9925     *
9926     * @param left The left coordinate of the rectangle to invalidate.
9927     * @param top The top coordinate of the rectangle to invalidate.
9928     * @param right The right coordinate of the rectangle to invalidate.
9929     * @param bottom The bottom coordinate of the rectangle to invalidate.
9930     *
9931     * @see #invalidate(int, int, int, int)
9932     * @see #invalidate(Rect)
9933     * @see #postInvalidateDelayed(long, int, int, int, int)
9934     */
9935    public void postInvalidate(int left, int top, int right, int bottom) {
9936        postInvalidateDelayed(0, left, top, right, bottom);
9937    }
9938
9939    /**
9940     * <p>Cause an invalidate to happen on a subsequent cycle through the event
9941     * loop. Waits for the specified amount of time.</p>
9942     *
9943     * <p>This method can be invoked from outside of the UI thread
9944     * only when this View is attached to a window.</p>
9945     *
9946     * @param delayMilliseconds the duration in milliseconds to delay the
9947     *         invalidation by
9948     *
9949     * @see #invalidate()
9950     * @see #postInvalidate()
9951     */
9952    public void postInvalidateDelayed(long delayMilliseconds) {
9953        // We try only with the AttachInfo because there's no point in invalidating
9954        // if we are not attached to our window
9955        final AttachInfo attachInfo = mAttachInfo;
9956        if (attachInfo != null) {
9957            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
9958        }
9959    }
9960
9961    /**
9962     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9963     * through the event loop. Waits for the specified amount of time.</p>
9964     *
9965     * <p>This method can be invoked from outside of the UI thread
9966     * only when this View is attached to a window.</p>
9967     *
9968     * @param delayMilliseconds the duration in milliseconds to delay the
9969     *         invalidation by
9970     * @param left The left coordinate of the rectangle to invalidate.
9971     * @param top The top coordinate of the rectangle to invalidate.
9972     * @param right The right coordinate of the rectangle to invalidate.
9973     * @param bottom The bottom coordinate of the rectangle to invalidate.
9974     *
9975     * @see #invalidate(int, int, int, int)
9976     * @see #invalidate(Rect)
9977     * @see #postInvalidate(int, int, int, int)
9978     */
9979    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
9980            int right, int bottom) {
9981
9982        // We try only with the AttachInfo because there's no point in invalidating
9983        // if we are not attached to our window
9984        final AttachInfo attachInfo = mAttachInfo;
9985        if (attachInfo != null) {
9986            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9987            info.target = this;
9988            info.left = left;
9989            info.top = top;
9990            info.right = right;
9991            info.bottom = bottom;
9992
9993            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
9994        }
9995    }
9996
9997    /**
9998     * <p>Cause an invalidate to happen on the next animation time step, typically the
9999     * next display frame.</p>
10000     *
10001     * <p>This method can be invoked from outside of the UI thread
10002     * only when this View is attached to a window.</p>
10003     *
10004     * @see #invalidate()
10005     */
10006    public void postInvalidateOnAnimation() {
10007        // We try only with the AttachInfo because there's no point in invalidating
10008        // if we are not attached to our window
10009        final AttachInfo attachInfo = mAttachInfo;
10010        if (attachInfo != null) {
10011            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10012        }
10013    }
10014
10015    /**
10016     * <p>Cause an invalidate of the specified area to happen on the next animation
10017     * time step, typically the next display frame.</p>
10018     *
10019     * <p>This method can be invoked from outside of the UI thread
10020     * only when this View is attached to a window.</p>
10021     *
10022     * @param left The left coordinate of the rectangle to invalidate.
10023     * @param top The top coordinate of the rectangle to invalidate.
10024     * @param right The right coordinate of the rectangle to invalidate.
10025     * @param bottom The bottom coordinate of the rectangle to invalidate.
10026     *
10027     * @see #invalidate(int, int, int, int)
10028     * @see #invalidate(Rect)
10029     */
10030    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10031        // We try only with the AttachInfo because there's no point in invalidating
10032        // if we are not attached to our window
10033        final AttachInfo attachInfo = mAttachInfo;
10034        if (attachInfo != null) {
10035            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10036            info.target = this;
10037            info.left = left;
10038            info.top = top;
10039            info.right = right;
10040            info.bottom = bottom;
10041
10042            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10043        }
10044    }
10045
10046    /**
10047     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10048     * This event is sent at most once every
10049     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10050     */
10051    private void postSendViewScrolledAccessibilityEventCallback() {
10052        if (mSendViewScrolledAccessibilityEvent == null) {
10053            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10054        }
10055        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10056            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10057            postDelayed(mSendViewScrolledAccessibilityEvent,
10058                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10059        }
10060    }
10061
10062    /**
10063     * Called by a parent to request that a child update its values for mScrollX
10064     * and mScrollY if necessary. This will typically be done if the child is
10065     * animating a scroll using a {@link android.widget.Scroller Scroller}
10066     * object.
10067     */
10068    public void computeScroll() {
10069    }
10070
10071    /**
10072     * <p>Indicate whether the horizontal edges are faded when the view is
10073     * scrolled horizontally.</p>
10074     *
10075     * @return true if the horizontal edges should are faded on scroll, false
10076     *         otherwise
10077     *
10078     * @see #setHorizontalFadingEdgeEnabled(boolean)
10079     *
10080     * @attr ref android.R.styleable#View_requiresFadingEdge
10081     */
10082    public boolean isHorizontalFadingEdgeEnabled() {
10083        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10084    }
10085
10086    /**
10087     * <p>Define whether the horizontal edges should be faded when this view
10088     * is scrolled horizontally.</p>
10089     *
10090     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10091     *                                    be faded when the view is scrolled
10092     *                                    horizontally
10093     *
10094     * @see #isHorizontalFadingEdgeEnabled()
10095     *
10096     * @attr ref android.R.styleable#View_requiresFadingEdge
10097     */
10098    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10099        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10100            if (horizontalFadingEdgeEnabled) {
10101                initScrollCache();
10102            }
10103
10104            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10105        }
10106    }
10107
10108    /**
10109     * <p>Indicate whether the vertical edges are faded when the view is
10110     * scrolled horizontally.</p>
10111     *
10112     * @return true if the vertical edges should are faded on scroll, false
10113     *         otherwise
10114     *
10115     * @see #setVerticalFadingEdgeEnabled(boolean)
10116     *
10117     * @attr ref android.R.styleable#View_requiresFadingEdge
10118     */
10119    public boolean isVerticalFadingEdgeEnabled() {
10120        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10121    }
10122
10123    /**
10124     * <p>Define whether the vertical edges should be faded when this view
10125     * is scrolled vertically.</p>
10126     *
10127     * @param verticalFadingEdgeEnabled true if the vertical edges should
10128     *                                  be faded when the view is scrolled
10129     *                                  vertically
10130     *
10131     * @see #isVerticalFadingEdgeEnabled()
10132     *
10133     * @attr ref android.R.styleable#View_requiresFadingEdge
10134     */
10135    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10136        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10137            if (verticalFadingEdgeEnabled) {
10138                initScrollCache();
10139            }
10140
10141            mViewFlags ^= FADING_EDGE_VERTICAL;
10142        }
10143    }
10144
10145    /**
10146     * Returns the strength, or intensity, of the top faded edge. The strength is
10147     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10148     * returns 0.0 or 1.0 but no value in between.
10149     *
10150     * Subclasses should override this method to provide a smoother fade transition
10151     * when scrolling occurs.
10152     *
10153     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10154     */
10155    protected float getTopFadingEdgeStrength() {
10156        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10157    }
10158
10159    /**
10160     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10161     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10162     * returns 0.0 or 1.0 but no value in between.
10163     *
10164     * Subclasses should override this method to provide a smoother fade transition
10165     * when scrolling occurs.
10166     *
10167     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10168     */
10169    protected float getBottomFadingEdgeStrength() {
10170        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10171                computeVerticalScrollRange() ? 1.0f : 0.0f;
10172    }
10173
10174    /**
10175     * Returns the strength, or intensity, of the left faded edge. The strength is
10176     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10177     * returns 0.0 or 1.0 but no value in between.
10178     *
10179     * Subclasses should override this method to provide a smoother fade transition
10180     * when scrolling occurs.
10181     *
10182     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10183     */
10184    protected float getLeftFadingEdgeStrength() {
10185        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10186    }
10187
10188    /**
10189     * Returns the strength, or intensity, of the right faded edge. The strength is
10190     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10191     * returns 0.0 or 1.0 but no value in between.
10192     *
10193     * Subclasses should override this method to provide a smoother fade transition
10194     * when scrolling occurs.
10195     *
10196     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10197     */
10198    protected float getRightFadingEdgeStrength() {
10199        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10200                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10201    }
10202
10203    /**
10204     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10205     * scrollbar is not drawn by default.</p>
10206     *
10207     * @return true if the horizontal scrollbar should be painted, false
10208     *         otherwise
10209     *
10210     * @see #setHorizontalScrollBarEnabled(boolean)
10211     */
10212    public boolean isHorizontalScrollBarEnabled() {
10213        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10214    }
10215
10216    /**
10217     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10218     * scrollbar is not drawn by default.</p>
10219     *
10220     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10221     *                                   be painted
10222     *
10223     * @see #isHorizontalScrollBarEnabled()
10224     */
10225    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10226        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10227            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10228            computeOpaqueFlags();
10229            resolvePadding();
10230        }
10231    }
10232
10233    /**
10234     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10235     * scrollbar is not drawn by default.</p>
10236     *
10237     * @return true if the vertical scrollbar should be painted, false
10238     *         otherwise
10239     *
10240     * @see #setVerticalScrollBarEnabled(boolean)
10241     */
10242    public boolean isVerticalScrollBarEnabled() {
10243        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10244    }
10245
10246    /**
10247     * <p>Define whether the vertical scrollbar should be drawn or not. The
10248     * scrollbar is not drawn by default.</p>
10249     *
10250     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10251     *                                 be painted
10252     *
10253     * @see #isVerticalScrollBarEnabled()
10254     */
10255    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10256        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10257            mViewFlags ^= SCROLLBARS_VERTICAL;
10258            computeOpaqueFlags();
10259            resolvePadding();
10260        }
10261    }
10262
10263    /**
10264     * @hide
10265     */
10266    protected void recomputePadding() {
10267        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10268    }
10269
10270    /**
10271     * Define whether scrollbars will fade when the view is not scrolling.
10272     *
10273     * @param fadeScrollbars wheter to enable fading
10274     *
10275     * @attr ref android.R.styleable#View_fadeScrollbars
10276     */
10277    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10278        initScrollCache();
10279        final ScrollabilityCache scrollabilityCache = mScrollCache;
10280        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10281        if (fadeScrollbars) {
10282            scrollabilityCache.state = ScrollabilityCache.OFF;
10283        } else {
10284            scrollabilityCache.state = ScrollabilityCache.ON;
10285        }
10286    }
10287
10288    /**
10289     *
10290     * Returns true if scrollbars will fade when this view is not scrolling
10291     *
10292     * @return true if scrollbar fading is enabled
10293     *
10294     * @attr ref android.R.styleable#View_fadeScrollbars
10295     */
10296    public boolean isScrollbarFadingEnabled() {
10297        return mScrollCache != null && mScrollCache.fadeScrollBars;
10298    }
10299
10300    /**
10301     *
10302     * Returns the delay before scrollbars fade.
10303     *
10304     * @return the delay before scrollbars fade
10305     *
10306     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10307     */
10308    public int getScrollBarDefaultDelayBeforeFade() {
10309        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10310                mScrollCache.scrollBarDefaultDelayBeforeFade;
10311    }
10312
10313    /**
10314     * Define the delay before scrollbars fade.
10315     *
10316     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10317     *
10318     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10319     */
10320    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10321        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10322    }
10323
10324    /**
10325     *
10326     * Returns the scrollbar fade duration.
10327     *
10328     * @return the scrollbar fade duration
10329     *
10330     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10331     */
10332    public int getScrollBarFadeDuration() {
10333        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10334                mScrollCache.scrollBarFadeDuration;
10335    }
10336
10337    /**
10338     * Define the scrollbar fade duration.
10339     *
10340     * @param scrollBarFadeDuration - the scrollbar fade duration
10341     *
10342     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10343     */
10344    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10345        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10346    }
10347
10348    /**
10349     *
10350     * Returns the scrollbar size.
10351     *
10352     * @return the scrollbar size
10353     *
10354     * @attr ref android.R.styleable#View_scrollbarSize
10355     */
10356    public int getScrollBarSize() {
10357        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10358                mScrollCache.scrollBarSize;
10359    }
10360
10361    /**
10362     * Define the scrollbar size.
10363     *
10364     * @param scrollBarSize - the scrollbar size
10365     *
10366     * @attr ref android.R.styleable#View_scrollbarSize
10367     */
10368    public void setScrollBarSize(int scrollBarSize) {
10369        getScrollCache().scrollBarSize = scrollBarSize;
10370    }
10371
10372    /**
10373     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10374     * inset. When inset, they add to the padding of the view. And the scrollbars
10375     * can be drawn inside the padding area or on the edge of the view. For example,
10376     * if a view has a background drawable and you want to draw the scrollbars
10377     * inside the padding specified by the drawable, you can use
10378     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10379     * appear at the edge of the view, ignoring the padding, then you can use
10380     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10381     * @param style the style of the scrollbars. Should be one of
10382     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10383     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10384     * @see #SCROLLBARS_INSIDE_OVERLAY
10385     * @see #SCROLLBARS_INSIDE_INSET
10386     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10387     * @see #SCROLLBARS_OUTSIDE_INSET
10388     *
10389     * @attr ref android.R.styleable#View_scrollbarStyle
10390     */
10391    public void setScrollBarStyle(int style) {
10392        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10393            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10394            computeOpaqueFlags();
10395            resolvePadding();
10396        }
10397    }
10398
10399    /**
10400     * <p>Returns the current scrollbar style.</p>
10401     * @return the current scrollbar style
10402     * @see #SCROLLBARS_INSIDE_OVERLAY
10403     * @see #SCROLLBARS_INSIDE_INSET
10404     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10405     * @see #SCROLLBARS_OUTSIDE_INSET
10406     *
10407     * @attr ref android.R.styleable#View_scrollbarStyle
10408     */
10409    @ViewDebug.ExportedProperty(mapping = {
10410            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10411            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10412            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10413            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10414    })
10415    public int getScrollBarStyle() {
10416        return mViewFlags & SCROLLBARS_STYLE_MASK;
10417    }
10418
10419    /**
10420     * <p>Compute the horizontal range that the horizontal scrollbar
10421     * represents.</p>
10422     *
10423     * <p>The range is expressed in arbitrary units that must be the same as the
10424     * units used by {@link #computeHorizontalScrollExtent()} and
10425     * {@link #computeHorizontalScrollOffset()}.</p>
10426     *
10427     * <p>The default range is the drawing width of this view.</p>
10428     *
10429     * @return the total horizontal range represented by the horizontal
10430     *         scrollbar
10431     *
10432     * @see #computeHorizontalScrollExtent()
10433     * @see #computeHorizontalScrollOffset()
10434     * @see android.widget.ScrollBarDrawable
10435     */
10436    protected int computeHorizontalScrollRange() {
10437        return getWidth();
10438    }
10439
10440    /**
10441     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10442     * within the horizontal range. This value is used to compute the position
10443     * of the thumb within the scrollbar's track.</p>
10444     *
10445     * <p>The range is expressed in arbitrary units that must be the same as the
10446     * units used by {@link #computeHorizontalScrollRange()} and
10447     * {@link #computeHorizontalScrollExtent()}.</p>
10448     *
10449     * <p>The default offset is the scroll offset of this view.</p>
10450     *
10451     * @return the horizontal offset of the scrollbar's thumb
10452     *
10453     * @see #computeHorizontalScrollRange()
10454     * @see #computeHorizontalScrollExtent()
10455     * @see android.widget.ScrollBarDrawable
10456     */
10457    protected int computeHorizontalScrollOffset() {
10458        return mScrollX;
10459    }
10460
10461    /**
10462     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10463     * within the horizontal range. This value is used to compute the length
10464     * of the thumb within the scrollbar's track.</p>
10465     *
10466     * <p>The range is expressed in arbitrary units that must be the same as the
10467     * units used by {@link #computeHorizontalScrollRange()} and
10468     * {@link #computeHorizontalScrollOffset()}.</p>
10469     *
10470     * <p>The default extent is the drawing width of this view.</p>
10471     *
10472     * @return the horizontal extent of the scrollbar's thumb
10473     *
10474     * @see #computeHorizontalScrollRange()
10475     * @see #computeHorizontalScrollOffset()
10476     * @see android.widget.ScrollBarDrawable
10477     */
10478    protected int computeHorizontalScrollExtent() {
10479        return getWidth();
10480    }
10481
10482    /**
10483     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10484     *
10485     * <p>The range is expressed in arbitrary units that must be the same as the
10486     * units used by {@link #computeVerticalScrollExtent()} and
10487     * {@link #computeVerticalScrollOffset()}.</p>
10488     *
10489     * @return the total vertical range represented by the vertical scrollbar
10490     *
10491     * <p>The default range is the drawing height of this view.</p>
10492     *
10493     * @see #computeVerticalScrollExtent()
10494     * @see #computeVerticalScrollOffset()
10495     * @see android.widget.ScrollBarDrawable
10496     */
10497    protected int computeVerticalScrollRange() {
10498        return getHeight();
10499    }
10500
10501    /**
10502     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10503     * within the horizontal range. This value is used to compute the position
10504     * of the thumb within the scrollbar's track.</p>
10505     *
10506     * <p>The range is expressed in arbitrary units that must be the same as the
10507     * units used by {@link #computeVerticalScrollRange()} and
10508     * {@link #computeVerticalScrollExtent()}.</p>
10509     *
10510     * <p>The default offset is the scroll offset of this view.</p>
10511     *
10512     * @return the vertical offset of the scrollbar's thumb
10513     *
10514     * @see #computeVerticalScrollRange()
10515     * @see #computeVerticalScrollExtent()
10516     * @see android.widget.ScrollBarDrawable
10517     */
10518    protected int computeVerticalScrollOffset() {
10519        return mScrollY;
10520    }
10521
10522    /**
10523     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10524     * within the vertical range. This value is used to compute the length
10525     * of the thumb within the scrollbar's track.</p>
10526     *
10527     * <p>The range is expressed in arbitrary units that must be the same as the
10528     * units used by {@link #computeVerticalScrollRange()} and
10529     * {@link #computeVerticalScrollOffset()}.</p>
10530     *
10531     * <p>The default extent is the drawing height of this view.</p>
10532     *
10533     * @return the vertical extent of the scrollbar's thumb
10534     *
10535     * @see #computeVerticalScrollRange()
10536     * @see #computeVerticalScrollOffset()
10537     * @see android.widget.ScrollBarDrawable
10538     */
10539    protected int computeVerticalScrollExtent() {
10540        return getHeight();
10541    }
10542
10543    /**
10544     * Check if this view can be scrolled horizontally in a certain direction.
10545     *
10546     * @param direction Negative to check scrolling left, positive to check scrolling right.
10547     * @return true if this view can be scrolled in the specified direction, false otherwise.
10548     */
10549    public boolean canScrollHorizontally(int direction) {
10550        final int offset = computeHorizontalScrollOffset();
10551        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10552        if (range == 0) return false;
10553        if (direction < 0) {
10554            return offset > 0;
10555        } else {
10556            return offset < range - 1;
10557        }
10558    }
10559
10560    /**
10561     * Check if this view can be scrolled vertically in a certain direction.
10562     *
10563     * @param direction Negative to check scrolling up, positive to check scrolling down.
10564     * @return true if this view can be scrolled in the specified direction, false otherwise.
10565     */
10566    public boolean canScrollVertically(int direction) {
10567        final int offset = computeVerticalScrollOffset();
10568        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10569        if (range == 0) return false;
10570        if (direction < 0) {
10571            return offset > 0;
10572        } else {
10573            return offset < range - 1;
10574        }
10575    }
10576
10577    /**
10578     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10579     * scrollbars are painted only if they have been awakened first.</p>
10580     *
10581     * @param canvas the canvas on which to draw the scrollbars
10582     *
10583     * @see #awakenScrollBars(int)
10584     */
10585    protected final void onDrawScrollBars(Canvas canvas) {
10586        // scrollbars are drawn only when the animation is running
10587        final ScrollabilityCache cache = mScrollCache;
10588        if (cache != null) {
10589
10590            int state = cache.state;
10591
10592            if (state == ScrollabilityCache.OFF) {
10593                return;
10594            }
10595
10596            boolean invalidate = false;
10597
10598            if (state == ScrollabilityCache.FADING) {
10599                // We're fading -- get our fade interpolation
10600                if (cache.interpolatorValues == null) {
10601                    cache.interpolatorValues = new float[1];
10602                }
10603
10604                float[] values = cache.interpolatorValues;
10605
10606                // Stops the animation if we're done
10607                if (cache.scrollBarInterpolator.timeToValues(values) ==
10608                        Interpolator.Result.FREEZE_END) {
10609                    cache.state = ScrollabilityCache.OFF;
10610                } else {
10611                    cache.scrollBar.setAlpha(Math.round(values[0]));
10612                }
10613
10614                // This will make the scroll bars inval themselves after
10615                // drawing. We only want this when we're fading so that
10616                // we prevent excessive redraws
10617                invalidate = true;
10618            } else {
10619                // We're just on -- but we may have been fading before so
10620                // reset alpha
10621                cache.scrollBar.setAlpha(255);
10622            }
10623
10624
10625            final int viewFlags = mViewFlags;
10626
10627            final boolean drawHorizontalScrollBar =
10628                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10629            final boolean drawVerticalScrollBar =
10630                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10631                && !isVerticalScrollBarHidden();
10632
10633            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10634                final int width = mRight - mLeft;
10635                final int height = mBottom - mTop;
10636
10637                final ScrollBarDrawable scrollBar = cache.scrollBar;
10638
10639                final int scrollX = mScrollX;
10640                final int scrollY = mScrollY;
10641                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10642
10643                int left, top, right, bottom;
10644
10645                if (drawHorizontalScrollBar) {
10646                    int size = scrollBar.getSize(false);
10647                    if (size <= 0) {
10648                        size = cache.scrollBarSize;
10649                    }
10650
10651                    scrollBar.setParameters(computeHorizontalScrollRange(),
10652                                            computeHorizontalScrollOffset(),
10653                                            computeHorizontalScrollExtent(), false);
10654                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10655                            getVerticalScrollbarWidth() : 0;
10656                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10657                    left = scrollX + (mPaddingLeft & inside);
10658                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10659                    bottom = top + size;
10660                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10661                    if (invalidate) {
10662                        invalidate(left, top, right, bottom);
10663                    }
10664                }
10665
10666                if (drawVerticalScrollBar) {
10667                    int size = scrollBar.getSize(true);
10668                    if (size <= 0) {
10669                        size = cache.scrollBarSize;
10670                    }
10671
10672                    scrollBar.setParameters(computeVerticalScrollRange(),
10673                                            computeVerticalScrollOffset(),
10674                                            computeVerticalScrollExtent(), true);
10675                    switch (mVerticalScrollbarPosition) {
10676                        default:
10677                        case SCROLLBAR_POSITION_DEFAULT:
10678                        case SCROLLBAR_POSITION_RIGHT:
10679                            left = scrollX + width - size - (mUserPaddingRight & inside);
10680                            break;
10681                        case SCROLLBAR_POSITION_LEFT:
10682                            left = scrollX + (mUserPaddingLeft & inside);
10683                            break;
10684                    }
10685                    top = scrollY + (mPaddingTop & inside);
10686                    right = left + size;
10687                    bottom = scrollY + height - (mUserPaddingBottom & inside);
10688                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
10689                    if (invalidate) {
10690                        invalidate(left, top, right, bottom);
10691                    }
10692                }
10693            }
10694        }
10695    }
10696
10697    /**
10698     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
10699     * FastScroller is visible.
10700     * @return whether to temporarily hide the vertical scrollbar
10701     * @hide
10702     */
10703    protected boolean isVerticalScrollBarHidden() {
10704        return false;
10705    }
10706
10707    /**
10708     * <p>Draw the horizontal scrollbar if
10709     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
10710     *
10711     * @param canvas the canvas on which to draw the scrollbar
10712     * @param scrollBar the scrollbar's drawable
10713     *
10714     * @see #isHorizontalScrollBarEnabled()
10715     * @see #computeHorizontalScrollRange()
10716     * @see #computeHorizontalScrollExtent()
10717     * @see #computeHorizontalScrollOffset()
10718     * @see android.widget.ScrollBarDrawable
10719     * @hide
10720     */
10721    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
10722            int l, int t, int r, int b) {
10723        scrollBar.setBounds(l, t, r, b);
10724        scrollBar.draw(canvas);
10725    }
10726
10727    /**
10728     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
10729     * returns true.</p>
10730     *
10731     * @param canvas the canvas on which to draw the scrollbar
10732     * @param scrollBar the scrollbar's drawable
10733     *
10734     * @see #isVerticalScrollBarEnabled()
10735     * @see #computeVerticalScrollRange()
10736     * @see #computeVerticalScrollExtent()
10737     * @see #computeVerticalScrollOffset()
10738     * @see android.widget.ScrollBarDrawable
10739     * @hide
10740     */
10741    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
10742            int l, int t, int r, int b) {
10743        scrollBar.setBounds(l, t, r, b);
10744        scrollBar.draw(canvas);
10745    }
10746
10747    /**
10748     * Implement this to do your drawing.
10749     *
10750     * @param canvas the canvas on which the background will be drawn
10751     */
10752    protected void onDraw(Canvas canvas) {
10753    }
10754
10755    /*
10756     * Caller is responsible for calling requestLayout if necessary.
10757     * (This allows addViewInLayout to not request a new layout.)
10758     */
10759    void assignParent(ViewParent parent) {
10760        if (mParent == null) {
10761            mParent = parent;
10762        } else if (parent == null) {
10763            mParent = null;
10764        } else {
10765            throw new RuntimeException("view " + this + " being added, but"
10766                    + " it already has a parent");
10767        }
10768    }
10769
10770    /**
10771     * This is called when the view is attached to a window.  At this point it
10772     * has a Surface and will start drawing.  Note that this function is
10773     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
10774     * however it may be called any time before the first onDraw -- including
10775     * before or after {@link #onMeasure(int, int)}.
10776     *
10777     * @see #onDetachedFromWindow()
10778     */
10779    protected void onAttachedToWindow() {
10780        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
10781            mParent.requestTransparentRegion(this);
10782        }
10783        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
10784            initialAwakenScrollBars();
10785            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
10786        }
10787        jumpDrawablesToCurrentState();
10788        // Order is important here: LayoutDirection MUST be resolved before Padding
10789        // and TextDirection
10790        resolveLayoutDirection();
10791        resolvePadding();
10792        resolveTextDirection();
10793        resolveTextAlignment();
10794        clearAccessibilityFocus();
10795        if (isFocused()) {
10796            InputMethodManager imm = InputMethodManager.peekInstance();
10797            imm.focusIn(this);
10798        }
10799    }
10800
10801    /**
10802     * @see #onScreenStateChanged(int)
10803     */
10804    void dispatchScreenStateChanged(int screenState) {
10805        onScreenStateChanged(screenState);
10806    }
10807
10808    /**
10809     * This method is called whenever the state of the screen this view is
10810     * attached to changes. A state change will usually occurs when the screen
10811     * turns on or off (whether it happens automatically or the user does it
10812     * manually.)
10813     *
10814     * @param screenState The new state of the screen. Can be either
10815     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
10816     */
10817    public void onScreenStateChanged(int screenState) {
10818    }
10819
10820    /**
10821     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
10822     */
10823    private boolean hasRtlSupport() {
10824        return mContext.getApplicationInfo().hasRtlSupport();
10825    }
10826
10827    /**
10828     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
10829     * that the parent directionality can and will be resolved before its children.
10830     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
10831     */
10832    public void resolveLayoutDirection() {
10833        // Clear any previous layout direction resolution
10834        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10835
10836        if (hasRtlSupport()) {
10837            // Set resolved depending on layout direction
10838            switch (getLayoutDirection()) {
10839                case LAYOUT_DIRECTION_INHERIT:
10840                    // If this is root view, no need to look at parent's layout dir.
10841                    if (canResolveLayoutDirection()) {
10842                        ViewGroup viewGroup = ((ViewGroup) mParent);
10843
10844                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
10845                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10846                        }
10847                    } else {
10848                        // Nothing to do, LTR by default
10849                    }
10850                    break;
10851                case LAYOUT_DIRECTION_RTL:
10852                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10853                    break;
10854                case LAYOUT_DIRECTION_LOCALE:
10855                    if(isLayoutDirectionRtl(Locale.getDefault())) {
10856                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10857                    }
10858                    break;
10859                default:
10860                    // Nothing to do, LTR by default
10861            }
10862        }
10863
10864        // Set to resolved
10865        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
10866        onResolvedLayoutDirectionChanged();
10867        // Resolve padding
10868        resolvePadding();
10869    }
10870
10871    /**
10872     * Called when layout direction has been resolved.
10873     *
10874     * The default implementation does nothing.
10875     */
10876    public void onResolvedLayoutDirectionChanged() {
10877    }
10878
10879    /**
10880     * Resolve padding depending on layout direction.
10881     */
10882    public void resolvePadding() {
10883        // If the user specified the absolute padding (either with android:padding or
10884        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
10885        // use the default padding or the padding from the background drawable
10886        // (stored at this point in mPadding*)
10887        int resolvedLayoutDirection = getResolvedLayoutDirection();
10888        switch (resolvedLayoutDirection) {
10889            case LAYOUT_DIRECTION_RTL:
10890                // Start user padding override Right user padding. Otherwise, if Right user
10891                // padding is not defined, use the default Right padding. If Right user padding
10892                // is defined, just use it.
10893                if (mUserPaddingStart >= 0) {
10894                    mUserPaddingRight = mUserPaddingStart;
10895                } else if (mUserPaddingRight < 0) {
10896                    mUserPaddingRight = mPaddingRight;
10897                }
10898                if (mUserPaddingEnd >= 0) {
10899                    mUserPaddingLeft = mUserPaddingEnd;
10900                } else if (mUserPaddingLeft < 0) {
10901                    mUserPaddingLeft = mPaddingLeft;
10902                }
10903                break;
10904            case LAYOUT_DIRECTION_LTR:
10905            default:
10906                // Start user padding override Left user padding. Otherwise, if Left user
10907                // padding is not defined, use the default left padding. If Left user padding
10908                // is defined, just use it.
10909                if (mUserPaddingStart >= 0) {
10910                    mUserPaddingLeft = mUserPaddingStart;
10911                } else if (mUserPaddingLeft < 0) {
10912                    mUserPaddingLeft = mPaddingLeft;
10913                }
10914                if (mUserPaddingEnd >= 0) {
10915                    mUserPaddingRight = mUserPaddingEnd;
10916                } else if (mUserPaddingRight < 0) {
10917                    mUserPaddingRight = mPaddingRight;
10918                }
10919        }
10920
10921        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
10922
10923        if(isPaddingRelative()) {
10924            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
10925        } else {
10926            recomputePadding();
10927        }
10928        onPaddingChanged(resolvedLayoutDirection);
10929    }
10930
10931    /**
10932     * Resolve padding depending on the layout direction. Subclasses that care about
10933     * padding resolution should override this method. The default implementation does
10934     * nothing.
10935     *
10936     * @param layoutDirection the direction of the layout
10937     *
10938     * @see {@link #LAYOUT_DIRECTION_LTR}
10939     * @see {@link #LAYOUT_DIRECTION_RTL}
10940     */
10941    public void onPaddingChanged(int layoutDirection) {
10942    }
10943
10944    /**
10945     * Check if layout direction resolution can be done.
10946     *
10947     * @return true if layout direction resolution can be done otherwise return false.
10948     */
10949    public boolean canResolveLayoutDirection() {
10950        switch (getLayoutDirection()) {
10951            case LAYOUT_DIRECTION_INHERIT:
10952                return (mParent != null) && (mParent instanceof ViewGroup);
10953            default:
10954                return true;
10955        }
10956    }
10957
10958    /**
10959     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
10960     * when reset is done.
10961     */
10962    public void resetResolvedLayoutDirection() {
10963        // Reset the current resolved bits
10964        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10965        onResolvedLayoutDirectionReset();
10966        // Reset also the text direction
10967        resetResolvedTextDirection();
10968    }
10969
10970    /**
10971     * Called during reset of resolved layout direction.
10972     *
10973     * Subclasses need to override this method to clear cached information that depends on the
10974     * resolved layout direction, or to inform child views that inherit their layout direction.
10975     *
10976     * The default implementation does nothing.
10977     */
10978    public void onResolvedLayoutDirectionReset() {
10979    }
10980
10981    /**
10982     * Check if a Locale uses an RTL script.
10983     *
10984     * @param locale Locale to check
10985     * @return true if the Locale uses an RTL script.
10986     */
10987    protected static boolean isLayoutDirectionRtl(Locale locale) {
10988        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
10989    }
10990
10991    /**
10992     * This is called when the view is detached from a window.  At this point it
10993     * no longer has a surface for drawing.
10994     *
10995     * @see #onAttachedToWindow()
10996     */
10997    protected void onDetachedFromWindow() {
10998        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
10999
11000        removeUnsetPressCallback();
11001        removeLongPressCallback();
11002        removePerformClickCallback();
11003        removeSendViewScrolledAccessibilityEventCallback();
11004
11005        destroyDrawingCache();
11006
11007        destroyLayer(false);
11008
11009        if (mAttachInfo != null) {
11010            if (mDisplayList != null) {
11011                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
11012            }
11013            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11014        } else {
11015            if (mDisplayList != null) {
11016                // Should never happen
11017                mDisplayList.invalidate();
11018            }
11019        }
11020
11021        mCurrentAnimation = null;
11022
11023        resetResolvedLayoutDirection();
11024        resetResolvedTextAlignment();
11025        resetAccessibilityStateChanged();
11026        clearAccessibilityFocus();
11027    }
11028
11029    /**
11030     * @return The number of times this view has been attached to a window
11031     */
11032    protected int getWindowAttachCount() {
11033        return mWindowAttachCount;
11034    }
11035
11036    /**
11037     * Retrieve a unique token identifying the window this view is attached to.
11038     * @return Return the window's token for use in
11039     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11040     */
11041    public IBinder getWindowToken() {
11042        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11043    }
11044
11045    /**
11046     * Retrieve a unique token identifying the top-level "real" window of
11047     * the window that this view is attached to.  That is, this is like
11048     * {@link #getWindowToken}, except if the window this view in is a panel
11049     * window (attached to another containing window), then the token of
11050     * the containing window is returned instead.
11051     *
11052     * @return Returns the associated window token, either
11053     * {@link #getWindowToken()} or the containing window's token.
11054     */
11055    public IBinder getApplicationWindowToken() {
11056        AttachInfo ai = mAttachInfo;
11057        if (ai != null) {
11058            IBinder appWindowToken = ai.mPanelParentWindowToken;
11059            if (appWindowToken == null) {
11060                appWindowToken = ai.mWindowToken;
11061            }
11062            return appWindowToken;
11063        }
11064        return null;
11065    }
11066
11067    /**
11068     * Retrieve private session object this view hierarchy is using to
11069     * communicate with the window manager.
11070     * @return the session object to communicate with the window manager
11071     */
11072    /*package*/ IWindowSession getWindowSession() {
11073        return mAttachInfo != null ? mAttachInfo.mSession : null;
11074    }
11075
11076    /**
11077     * @param info the {@link android.view.View.AttachInfo} to associated with
11078     *        this view
11079     */
11080    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11081        //System.out.println("Attached! " + this);
11082        mAttachInfo = info;
11083        mWindowAttachCount++;
11084        // We will need to evaluate the drawable state at least once.
11085        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11086        if (mFloatingTreeObserver != null) {
11087            info.mTreeObserver.merge(mFloatingTreeObserver);
11088            mFloatingTreeObserver = null;
11089        }
11090        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11091            mAttachInfo.mScrollContainers.add(this);
11092            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11093        }
11094        performCollectViewAttributes(mAttachInfo, visibility);
11095        onAttachedToWindow();
11096
11097        ListenerInfo li = mListenerInfo;
11098        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11099                li != null ? li.mOnAttachStateChangeListeners : null;
11100        if (listeners != null && listeners.size() > 0) {
11101            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11102            // perform the dispatching. The iterator is a safe guard against listeners that
11103            // could mutate the list by calling the various add/remove methods. This prevents
11104            // the array from being modified while we iterate it.
11105            for (OnAttachStateChangeListener listener : listeners) {
11106                listener.onViewAttachedToWindow(this);
11107            }
11108        }
11109
11110        int vis = info.mWindowVisibility;
11111        if (vis != GONE) {
11112            onWindowVisibilityChanged(vis);
11113        }
11114        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11115            // If nobody has evaluated the drawable state yet, then do it now.
11116            refreshDrawableState();
11117        }
11118    }
11119
11120    void dispatchDetachedFromWindow() {
11121        AttachInfo info = mAttachInfo;
11122        if (info != null) {
11123            int vis = info.mWindowVisibility;
11124            if (vis != GONE) {
11125                onWindowVisibilityChanged(GONE);
11126            }
11127        }
11128
11129        onDetachedFromWindow();
11130
11131        ListenerInfo li = mListenerInfo;
11132        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11133                li != null ? li.mOnAttachStateChangeListeners : null;
11134        if (listeners != null && listeners.size() > 0) {
11135            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11136            // perform the dispatching. The iterator is a safe guard against listeners that
11137            // could mutate the list by calling the various add/remove methods. This prevents
11138            // the array from being modified while we iterate it.
11139            for (OnAttachStateChangeListener listener : listeners) {
11140                listener.onViewDetachedFromWindow(this);
11141            }
11142        }
11143
11144        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11145            mAttachInfo.mScrollContainers.remove(this);
11146            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11147        }
11148
11149        mAttachInfo = null;
11150    }
11151
11152    /**
11153     * Store this view hierarchy's frozen state into the given container.
11154     *
11155     * @param container The SparseArray in which to save the view's state.
11156     *
11157     * @see #restoreHierarchyState(android.util.SparseArray)
11158     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11159     * @see #onSaveInstanceState()
11160     */
11161    public void saveHierarchyState(SparseArray<Parcelable> container) {
11162        dispatchSaveInstanceState(container);
11163    }
11164
11165    /**
11166     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11167     * this view and its children. May be overridden to modify how freezing happens to a
11168     * view's children; for example, some views may want to not store state for their children.
11169     *
11170     * @param container The SparseArray in which to save the view's state.
11171     *
11172     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11173     * @see #saveHierarchyState(android.util.SparseArray)
11174     * @see #onSaveInstanceState()
11175     */
11176    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11177        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11178            mPrivateFlags &= ~SAVE_STATE_CALLED;
11179            Parcelable state = onSaveInstanceState();
11180            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11181                throw new IllegalStateException(
11182                        "Derived class did not call super.onSaveInstanceState()");
11183            }
11184            if (state != null) {
11185                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11186                // + ": " + state);
11187                container.put(mID, state);
11188            }
11189        }
11190    }
11191
11192    /**
11193     * Hook allowing a view to generate a representation of its internal state
11194     * that can later be used to create a new instance with that same state.
11195     * This state should only contain information that is not persistent or can
11196     * not be reconstructed later. For example, you will never store your
11197     * current position on screen because that will be computed again when a
11198     * new instance of the view is placed in its view hierarchy.
11199     * <p>
11200     * Some examples of things you may store here: the current cursor position
11201     * in a text view (but usually not the text itself since that is stored in a
11202     * content provider or other persistent storage), the currently selected
11203     * item in a list view.
11204     *
11205     * @return Returns a Parcelable object containing the view's current dynamic
11206     *         state, or null if there is nothing interesting to save. The
11207     *         default implementation returns null.
11208     * @see #onRestoreInstanceState(android.os.Parcelable)
11209     * @see #saveHierarchyState(android.util.SparseArray)
11210     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11211     * @see #setSaveEnabled(boolean)
11212     */
11213    protected Parcelable onSaveInstanceState() {
11214        mPrivateFlags |= SAVE_STATE_CALLED;
11215        return BaseSavedState.EMPTY_STATE;
11216    }
11217
11218    /**
11219     * Restore this view hierarchy's frozen state from the given container.
11220     *
11221     * @param container The SparseArray which holds previously frozen states.
11222     *
11223     * @see #saveHierarchyState(android.util.SparseArray)
11224     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11225     * @see #onRestoreInstanceState(android.os.Parcelable)
11226     */
11227    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11228        dispatchRestoreInstanceState(container);
11229    }
11230
11231    /**
11232     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11233     * state for this view and its children. May be overridden to modify how restoring
11234     * happens to a view's children; for example, some views may want to not store state
11235     * for their children.
11236     *
11237     * @param container The SparseArray which holds previously saved state.
11238     *
11239     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11240     * @see #restoreHierarchyState(android.util.SparseArray)
11241     * @see #onRestoreInstanceState(android.os.Parcelable)
11242     */
11243    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11244        if (mID != NO_ID) {
11245            Parcelable state = container.get(mID);
11246            if (state != null) {
11247                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11248                // + ": " + state);
11249                mPrivateFlags &= ~SAVE_STATE_CALLED;
11250                onRestoreInstanceState(state);
11251                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11252                    throw new IllegalStateException(
11253                            "Derived class did not call super.onRestoreInstanceState()");
11254                }
11255            }
11256        }
11257    }
11258
11259    /**
11260     * Hook allowing a view to re-apply a representation of its internal state that had previously
11261     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11262     * null state.
11263     *
11264     * @param state The frozen state that had previously been returned by
11265     *        {@link #onSaveInstanceState}.
11266     *
11267     * @see #onSaveInstanceState()
11268     * @see #restoreHierarchyState(android.util.SparseArray)
11269     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11270     */
11271    protected void onRestoreInstanceState(Parcelable state) {
11272        mPrivateFlags |= SAVE_STATE_CALLED;
11273        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11274            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11275                    + "received " + state.getClass().toString() + " instead. This usually happens "
11276                    + "when two views of different type have the same id in the same hierarchy. "
11277                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11278                    + "other views do not use the same id.");
11279        }
11280    }
11281
11282    /**
11283     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11284     *
11285     * @return the drawing start time in milliseconds
11286     */
11287    public long getDrawingTime() {
11288        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11289    }
11290
11291    /**
11292     * <p>Enables or disables the duplication of the parent's state into this view. When
11293     * duplication is enabled, this view gets its drawable state from its parent rather
11294     * than from its own internal properties.</p>
11295     *
11296     * <p>Note: in the current implementation, setting this property to true after the
11297     * view was added to a ViewGroup might have no effect at all. This property should
11298     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11299     *
11300     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11301     * property is enabled, an exception will be thrown.</p>
11302     *
11303     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11304     * parent, these states should not be affected by this method.</p>
11305     *
11306     * @param enabled True to enable duplication of the parent's drawable state, false
11307     *                to disable it.
11308     *
11309     * @see #getDrawableState()
11310     * @see #isDuplicateParentStateEnabled()
11311     */
11312    public void setDuplicateParentStateEnabled(boolean enabled) {
11313        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11314    }
11315
11316    /**
11317     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11318     *
11319     * @return True if this view's drawable state is duplicated from the parent,
11320     *         false otherwise
11321     *
11322     * @see #getDrawableState()
11323     * @see #setDuplicateParentStateEnabled(boolean)
11324     */
11325    public boolean isDuplicateParentStateEnabled() {
11326        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11327    }
11328
11329    /**
11330     * <p>Specifies the type of layer backing this view. The layer can be
11331     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11332     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11333     *
11334     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11335     * instance that controls how the layer is composed on screen. The following
11336     * properties of the paint are taken into account when composing the layer:</p>
11337     * <ul>
11338     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11339     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11340     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11341     * </ul>
11342     *
11343     * <p>If this view has an alpha value set to < 1.0 by calling
11344     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11345     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11346     * equivalent to setting a hardware layer on this view and providing a paint with
11347     * the desired alpha value.<p>
11348     *
11349     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11350     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11351     * for more information on when and how to use layers.</p>
11352     *
11353     * @param layerType The ype of layer to use with this view, must be one of
11354     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11355     *        {@link #LAYER_TYPE_HARDWARE}
11356     * @param paint The paint used to compose the layer. This argument is optional
11357     *        and can be null. It is ignored when the layer type is
11358     *        {@link #LAYER_TYPE_NONE}
11359     *
11360     * @see #getLayerType()
11361     * @see #LAYER_TYPE_NONE
11362     * @see #LAYER_TYPE_SOFTWARE
11363     * @see #LAYER_TYPE_HARDWARE
11364     * @see #setAlpha(float)
11365     *
11366     * @attr ref android.R.styleable#View_layerType
11367     */
11368    public void setLayerType(int layerType, Paint paint) {
11369        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11370            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11371                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11372        }
11373
11374        if (layerType == mLayerType) {
11375            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11376                mLayerPaint = paint == null ? new Paint() : paint;
11377                invalidateParentCaches();
11378                invalidate(true);
11379            }
11380            return;
11381        }
11382
11383        // Destroy any previous software drawing cache if needed
11384        switch (mLayerType) {
11385            case LAYER_TYPE_HARDWARE:
11386                destroyLayer(false);
11387                // fall through - non-accelerated views may use software layer mechanism instead
11388            case LAYER_TYPE_SOFTWARE:
11389                destroyDrawingCache();
11390                break;
11391            default:
11392                break;
11393        }
11394
11395        mLayerType = layerType;
11396        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11397        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11398        mLocalDirtyRect = layerDisabled ? null : new Rect();
11399
11400        invalidateParentCaches();
11401        invalidate(true);
11402    }
11403
11404    /**
11405     * Indicates whether this view has a static layer. A view with layer type
11406     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11407     * dynamic.
11408     */
11409    boolean hasStaticLayer() {
11410        return true;
11411    }
11412
11413    /**
11414     * Indicates what type of layer is currently associated with this view. By default
11415     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11416     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11417     * for more information on the different types of layers.
11418     *
11419     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11420     *         {@link #LAYER_TYPE_HARDWARE}
11421     *
11422     * @see #setLayerType(int, android.graphics.Paint)
11423     * @see #buildLayer()
11424     * @see #LAYER_TYPE_NONE
11425     * @see #LAYER_TYPE_SOFTWARE
11426     * @see #LAYER_TYPE_HARDWARE
11427     */
11428    public int getLayerType() {
11429        return mLayerType;
11430    }
11431
11432    /**
11433     * Forces this view's layer to be created and this view to be rendered
11434     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11435     * invoking this method will have no effect.
11436     *
11437     * This method can for instance be used to render a view into its layer before
11438     * starting an animation. If this view is complex, rendering into the layer
11439     * before starting the animation will avoid skipping frames.
11440     *
11441     * @throws IllegalStateException If this view is not attached to a window
11442     *
11443     * @see #setLayerType(int, android.graphics.Paint)
11444     */
11445    public void buildLayer() {
11446        if (mLayerType == LAYER_TYPE_NONE) return;
11447
11448        if (mAttachInfo == null) {
11449            throw new IllegalStateException("This view must be attached to a window first");
11450        }
11451
11452        switch (mLayerType) {
11453            case LAYER_TYPE_HARDWARE:
11454                if (mAttachInfo.mHardwareRenderer != null &&
11455                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11456                        mAttachInfo.mHardwareRenderer.validate()) {
11457                    getHardwareLayer();
11458                }
11459                break;
11460            case LAYER_TYPE_SOFTWARE:
11461                buildDrawingCache(true);
11462                break;
11463        }
11464    }
11465
11466    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11467    void flushLayer() {
11468        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11469            mHardwareLayer.flush();
11470        }
11471    }
11472
11473    /**
11474     * <p>Returns a hardware layer that can be used to draw this view again
11475     * without executing its draw method.</p>
11476     *
11477     * @return A HardwareLayer ready to render, or null if an error occurred.
11478     */
11479    HardwareLayer getHardwareLayer() {
11480        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11481                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11482            return null;
11483        }
11484
11485        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11486
11487        final int width = mRight - mLeft;
11488        final int height = mBottom - mTop;
11489
11490        if (width == 0 || height == 0) {
11491            return null;
11492        }
11493
11494        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11495            if (mHardwareLayer == null) {
11496                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11497                        width, height, isOpaque());
11498                mLocalDirtyRect.set(0, 0, width, height);
11499            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11500                mHardwareLayer.resize(width, height);
11501                mLocalDirtyRect.set(0, 0, width, height);
11502            }
11503
11504            // The layer is not valid if the underlying GPU resources cannot be allocated
11505            if (!mHardwareLayer.isValid()) {
11506                return null;
11507            }
11508
11509            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11510            mLocalDirtyRect.setEmpty();
11511        }
11512
11513        return mHardwareLayer;
11514    }
11515
11516    /**
11517     * Destroys this View's hardware layer if possible.
11518     *
11519     * @return True if the layer was destroyed, false otherwise.
11520     *
11521     * @see #setLayerType(int, android.graphics.Paint)
11522     * @see #LAYER_TYPE_HARDWARE
11523     */
11524    boolean destroyLayer(boolean valid) {
11525        if (mHardwareLayer != null) {
11526            AttachInfo info = mAttachInfo;
11527            if (info != null && info.mHardwareRenderer != null &&
11528                    info.mHardwareRenderer.isEnabled() &&
11529                    (valid || info.mHardwareRenderer.validate())) {
11530                mHardwareLayer.destroy();
11531                mHardwareLayer = null;
11532
11533                invalidate(true);
11534                invalidateParentCaches();
11535            }
11536            return true;
11537        }
11538        return false;
11539    }
11540
11541    /**
11542     * Destroys all hardware rendering resources. This method is invoked
11543     * when the system needs to reclaim resources. Upon execution of this
11544     * method, you should free any OpenGL resources created by the view.
11545     *
11546     * Note: you <strong>must</strong> call
11547     * <code>super.destroyHardwareResources()</code> when overriding
11548     * this method.
11549     *
11550     * @hide
11551     */
11552    protected void destroyHardwareResources() {
11553        destroyLayer(true);
11554    }
11555
11556    /**
11557     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11558     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11559     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11560     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11561     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11562     * null.</p>
11563     *
11564     * <p>Enabling the drawing cache is similar to
11565     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11566     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11567     * drawing cache has no effect on rendering because the system uses a different mechanism
11568     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11569     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11570     * for information on how to enable software and hardware layers.</p>
11571     *
11572     * <p>This API can be used to manually generate
11573     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11574     * {@link #getDrawingCache()}.</p>
11575     *
11576     * @param enabled true to enable the drawing cache, false otherwise
11577     *
11578     * @see #isDrawingCacheEnabled()
11579     * @see #getDrawingCache()
11580     * @see #buildDrawingCache()
11581     * @see #setLayerType(int, android.graphics.Paint)
11582     */
11583    public void setDrawingCacheEnabled(boolean enabled) {
11584        mCachingFailed = false;
11585        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
11586    }
11587
11588    /**
11589     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11590     *
11591     * @return true if the drawing cache is enabled
11592     *
11593     * @see #setDrawingCacheEnabled(boolean)
11594     * @see #getDrawingCache()
11595     */
11596    @ViewDebug.ExportedProperty(category = "drawing")
11597    public boolean isDrawingCacheEnabled() {
11598        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11599    }
11600
11601    /**
11602     * Debugging utility which recursively outputs the dirty state of a view and its
11603     * descendants.
11604     *
11605     * @hide
11606     */
11607    @SuppressWarnings({"UnusedDeclaration"})
11608    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11609        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11610                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11611                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11612                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11613        if (clear) {
11614            mPrivateFlags &= clearMask;
11615        }
11616        if (this instanceof ViewGroup) {
11617            ViewGroup parent = (ViewGroup) this;
11618            final int count = parent.getChildCount();
11619            for (int i = 0; i < count; i++) {
11620                final View child = parent.getChildAt(i);
11621                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11622            }
11623        }
11624    }
11625
11626    /**
11627     * This method is used by ViewGroup to cause its children to restore or recreate their
11628     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11629     * to recreate its own display list, which would happen if it went through the normal
11630     * draw/dispatchDraw mechanisms.
11631     *
11632     * @hide
11633     */
11634    protected void dispatchGetDisplayList() {}
11635
11636    /**
11637     * A view that is not attached or hardware accelerated cannot create a display list.
11638     * This method checks these conditions and returns the appropriate result.
11639     *
11640     * @return true if view has the ability to create a display list, false otherwise.
11641     *
11642     * @hide
11643     */
11644    public boolean canHaveDisplayList() {
11645        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11646    }
11647
11648    /**
11649     * @return The HardwareRenderer associated with that view or null if hardware rendering
11650     * is not supported or this this has not been attached to a window.
11651     *
11652     * @hide
11653     */
11654    public HardwareRenderer getHardwareRenderer() {
11655        if (mAttachInfo != null) {
11656            return mAttachInfo.mHardwareRenderer;
11657        }
11658        return null;
11659    }
11660
11661    /**
11662     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11663     * Otherwise, the same display list will be returned (after having been rendered into
11664     * along the way, depending on the invalidation state of the view).
11665     *
11666     * @param displayList The previous version of this displayList, could be null.
11667     * @param isLayer Whether the requester of the display list is a layer. If so,
11668     * the view will avoid creating a layer inside the resulting display list.
11669     * @return A new or reused DisplayList object.
11670     */
11671    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
11672        if (!canHaveDisplayList()) {
11673            return null;
11674        }
11675
11676        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
11677                displayList == null || !displayList.isValid() ||
11678                (!isLayer && mRecreateDisplayList))) {
11679            // Don't need to recreate the display list, just need to tell our
11680            // children to restore/recreate theirs
11681            if (displayList != null && displayList.isValid() &&
11682                    !isLayer && !mRecreateDisplayList) {
11683                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11684                mPrivateFlags &= ~DIRTY_MASK;
11685                dispatchGetDisplayList();
11686
11687                return displayList;
11688            }
11689
11690            if (!isLayer) {
11691                // If we got here, we're recreating it. Mark it as such to ensure that
11692                // we copy in child display lists into ours in drawChild()
11693                mRecreateDisplayList = true;
11694            }
11695            if (displayList == null) {
11696                final String name = getClass().getSimpleName();
11697                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
11698                // If we're creating a new display list, make sure our parent gets invalidated
11699                // since they will need to recreate their display list to account for this
11700                // new child display list.
11701                invalidateParentCaches();
11702            }
11703
11704            boolean caching = false;
11705            final HardwareCanvas canvas = displayList.start();
11706            int restoreCount = 0;
11707            int width = mRight - mLeft;
11708            int height = mBottom - mTop;
11709
11710            try {
11711                canvas.setViewport(width, height);
11712                // The dirty rect should always be null for a display list
11713                canvas.onPreDraw(null);
11714                int layerType = (
11715                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
11716                        getLayerType() : LAYER_TYPE_NONE;
11717                if (!isLayer && layerType != LAYER_TYPE_NONE && USE_DISPLAY_LIST_PROPERTIES) {
11718                    if (layerType == LAYER_TYPE_HARDWARE) {
11719                        final HardwareLayer layer = getHardwareLayer();
11720                        if (layer != null && layer.isValid()) {
11721                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
11722                        } else {
11723                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
11724                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
11725                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11726                        }
11727                        caching = true;
11728                    } else {
11729                        buildDrawingCache(true);
11730                        Bitmap cache = getDrawingCache(true);
11731                        if (cache != null) {
11732                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
11733                            caching = true;
11734                        }
11735                    }
11736                } else {
11737
11738                    computeScroll();
11739
11740                    if (!USE_DISPLAY_LIST_PROPERTIES) {
11741                        restoreCount = canvas.save();
11742                    }
11743                    canvas.translate(-mScrollX, -mScrollY);
11744                    if (!isLayer) {
11745                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11746                        mPrivateFlags &= ~DIRTY_MASK;
11747                    }
11748
11749                    // Fast path for layouts with no backgrounds
11750                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11751                        dispatchDraw(canvas);
11752                    } else {
11753                        draw(canvas);
11754                    }
11755                }
11756            } finally {
11757                if (USE_DISPLAY_LIST_PROPERTIES) {
11758                    canvas.restoreToCount(restoreCount);
11759                }
11760                canvas.onPostDraw();
11761
11762                displayList.end();
11763                if (USE_DISPLAY_LIST_PROPERTIES) {
11764                    displayList.setCaching(caching);
11765                }
11766                if (isLayer && USE_DISPLAY_LIST_PROPERTIES) {
11767                    displayList.setLeftTopRightBottom(0, 0, width, height);
11768                } else {
11769                    setDisplayListProperties(displayList);
11770                }
11771            }
11772        } else if (!isLayer) {
11773            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11774            mPrivateFlags &= ~DIRTY_MASK;
11775        }
11776
11777        return displayList;
11778    }
11779
11780    /**
11781     * Get the DisplayList for the HardwareLayer
11782     *
11783     * @param layer The HardwareLayer whose DisplayList we want
11784     * @return A DisplayList fopr the specified HardwareLayer
11785     */
11786    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
11787        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
11788        layer.setDisplayList(displayList);
11789        return displayList;
11790    }
11791
11792
11793    /**
11794     * <p>Returns a display list that can be used to draw this view again
11795     * without executing its draw method.</p>
11796     *
11797     * @return A DisplayList ready to replay, or null if caching is not enabled.
11798     *
11799     * @hide
11800     */
11801    public DisplayList getDisplayList() {
11802        mDisplayList = getDisplayList(mDisplayList, false);
11803        return mDisplayList;
11804    }
11805
11806    /**
11807     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
11808     *
11809     * @return A non-scaled bitmap representing this view or null if cache is disabled.
11810     *
11811     * @see #getDrawingCache(boolean)
11812     */
11813    public Bitmap getDrawingCache() {
11814        return getDrawingCache(false);
11815    }
11816
11817    /**
11818     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
11819     * is null when caching is disabled. If caching is enabled and the cache is not ready,
11820     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
11821     * draw from the cache when the cache is enabled. To benefit from the cache, you must
11822     * request the drawing cache by calling this method and draw it on screen if the
11823     * returned bitmap is not null.</p>
11824     *
11825     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11826     * this method will create a bitmap of the same size as this view. Because this bitmap
11827     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11828     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11829     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11830     * size than the view. This implies that your application must be able to handle this
11831     * size.</p>
11832     *
11833     * @param autoScale Indicates whether the generated bitmap should be scaled based on
11834     *        the current density of the screen when the application is in compatibility
11835     *        mode.
11836     *
11837     * @return A bitmap representing this view or null if cache is disabled.
11838     *
11839     * @see #setDrawingCacheEnabled(boolean)
11840     * @see #isDrawingCacheEnabled()
11841     * @see #buildDrawingCache(boolean)
11842     * @see #destroyDrawingCache()
11843     */
11844    public Bitmap getDrawingCache(boolean autoScale) {
11845        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
11846            return null;
11847        }
11848        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
11849            buildDrawingCache(autoScale);
11850        }
11851        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
11852    }
11853
11854    /**
11855     * <p>Frees the resources used by the drawing cache. If you call
11856     * {@link #buildDrawingCache()} manually without calling
11857     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11858     * should cleanup the cache with this method afterwards.</p>
11859     *
11860     * @see #setDrawingCacheEnabled(boolean)
11861     * @see #buildDrawingCache()
11862     * @see #getDrawingCache()
11863     */
11864    public void destroyDrawingCache() {
11865        if (mDrawingCache != null) {
11866            mDrawingCache.recycle();
11867            mDrawingCache = null;
11868        }
11869        if (mUnscaledDrawingCache != null) {
11870            mUnscaledDrawingCache.recycle();
11871            mUnscaledDrawingCache = null;
11872        }
11873    }
11874
11875    /**
11876     * Setting a solid background color for the drawing cache's bitmaps will improve
11877     * performance and memory usage. Note, though that this should only be used if this
11878     * view will always be drawn on top of a solid color.
11879     *
11880     * @param color The background color to use for the drawing cache's bitmap
11881     *
11882     * @see #setDrawingCacheEnabled(boolean)
11883     * @see #buildDrawingCache()
11884     * @see #getDrawingCache()
11885     */
11886    public void setDrawingCacheBackgroundColor(int color) {
11887        if (color != mDrawingCacheBackgroundColor) {
11888            mDrawingCacheBackgroundColor = color;
11889            mPrivateFlags &= ~DRAWING_CACHE_VALID;
11890        }
11891    }
11892
11893    /**
11894     * @see #setDrawingCacheBackgroundColor(int)
11895     *
11896     * @return The background color to used for the drawing cache's bitmap
11897     */
11898    public int getDrawingCacheBackgroundColor() {
11899        return mDrawingCacheBackgroundColor;
11900    }
11901
11902    /**
11903     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
11904     *
11905     * @see #buildDrawingCache(boolean)
11906     */
11907    public void buildDrawingCache() {
11908        buildDrawingCache(false);
11909    }
11910
11911    /**
11912     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
11913     *
11914     * <p>If you call {@link #buildDrawingCache()} manually without calling
11915     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11916     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
11917     *
11918     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11919     * this method will create a bitmap of the same size as this view. Because this bitmap
11920     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11921     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11922     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11923     * size than the view. This implies that your application must be able to handle this
11924     * size.</p>
11925     *
11926     * <p>You should avoid calling this method when hardware acceleration is enabled. If
11927     * you do not need the drawing cache bitmap, calling this method will increase memory
11928     * usage and cause the view to be rendered in software once, thus negatively impacting
11929     * performance.</p>
11930     *
11931     * @see #getDrawingCache()
11932     * @see #destroyDrawingCache()
11933     */
11934    public void buildDrawingCache(boolean autoScale) {
11935        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
11936                mDrawingCache == null : mUnscaledDrawingCache == null)) {
11937            mCachingFailed = false;
11938
11939            if (ViewDebug.TRACE_HIERARCHY) {
11940                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
11941            }
11942
11943            int width = mRight - mLeft;
11944            int height = mBottom - mTop;
11945
11946            final AttachInfo attachInfo = mAttachInfo;
11947            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
11948
11949            if (autoScale && scalingRequired) {
11950                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
11951                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
11952            }
11953
11954            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
11955            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
11956            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
11957
11958            if (width <= 0 || height <= 0 ||
11959                     // Projected bitmap size in bytes
11960                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
11961                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
11962                destroyDrawingCache();
11963                mCachingFailed = true;
11964                return;
11965            }
11966
11967            boolean clear = true;
11968            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
11969
11970            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
11971                Bitmap.Config quality;
11972                if (!opaque) {
11973                    // Never pick ARGB_4444 because it looks awful
11974                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
11975                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
11976                        case DRAWING_CACHE_QUALITY_AUTO:
11977                            quality = Bitmap.Config.ARGB_8888;
11978                            break;
11979                        case DRAWING_CACHE_QUALITY_LOW:
11980                            quality = Bitmap.Config.ARGB_8888;
11981                            break;
11982                        case DRAWING_CACHE_QUALITY_HIGH:
11983                            quality = Bitmap.Config.ARGB_8888;
11984                            break;
11985                        default:
11986                            quality = Bitmap.Config.ARGB_8888;
11987                            break;
11988                    }
11989                } else {
11990                    // Optimization for translucent windows
11991                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
11992                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
11993                }
11994
11995                // Try to cleanup memory
11996                if (bitmap != null) bitmap.recycle();
11997
11998                try {
11999                    bitmap = Bitmap.createBitmap(width, height, quality);
12000                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12001                    if (autoScale) {
12002                        mDrawingCache = bitmap;
12003                    } else {
12004                        mUnscaledDrawingCache = bitmap;
12005                    }
12006                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12007                } catch (OutOfMemoryError e) {
12008                    // If there is not enough memory to create the bitmap cache, just
12009                    // ignore the issue as bitmap caches are not required to draw the
12010                    // view hierarchy
12011                    if (autoScale) {
12012                        mDrawingCache = null;
12013                    } else {
12014                        mUnscaledDrawingCache = null;
12015                    }
12016                    mCachingFailed = true;
12017                    return;
12018                }
12019
12020                clear = drawingCacheBackgroundColor != 0;
12021            }
12022
12023            Canvas canvas;
12024            if (attachInfo != null) {
12025                canvas = attachInfo.mCanvas;
12026                if (canvas == null) {
12027                    canvas = new Canvas();
12028                }
12029                canvas.setBitmap(bitmap);
12030                // Temporarily clobber the cached Canvas in case one of our children
12031                // is also using a drawing cache. Without this, the children would
12032                // steal the canvas by attaching their own bitmap to it and bad, bad
12033                // thing would happen (invisible views, corrupted drawings, etc.)
12034                attachInfo.mCanvas = null;
12035            } else {
12036                // This case should hopefully never or seldom happen
12037                canvas = new Canvas(bitmap);
12038            }
12039
12040            if (clear) {
12041                bitmap.eraseColor(drawingCacheBackgroundColor);
12042            }
12043
12044            computeScroll();
12045            final int restoreCount = canvas.save();
12046
12047            if (autoScale && scalingRequired) {
12048                final float scale = attachInfo.mApplicationScale;
12049                canvas.scale(scale, scale);
12050            }
12051
12052            canvas.translate(-mScrollX, -mScrollY);
12053
12054            mPrivateFlags |= DRAWN;
12055            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12056                    mLayerType != LAYER_TYPE_NONE) {
12057                mPrivateFlags |= DRAWING_CACHE_VALID;
12058            }
12059
12060            // Fast path for layouts with no backgrounds
12061            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12062                if (ViewDebug.TRACE_HIERARCHY) {
12063                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12064                }
12065                mPrivateFlags &= ~DIRTY_MASK;
12066                dispatchDraw(canvas);
12067            } else {
12068                draw(canvas);
12069            }
12070
12071            canvas.restoreToCount(restoreCount);
12072            canvas.setBitmap(null);
12073
12074            if (attachInfo != null) {
12075                // Restore the cached Canvas for our siblings
12076                attachInfo.mCanvas = canvas;
12077            }
12078        }
12079    }
12080
12081    /**
12082     * Create a snapshot of the view into a bitmap.  We should probably make
12083     * some form of this public, but should think about the API.
12084     */
12085    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12086        int width = mRight - mLeft;
12087        int height = mBottom - mTop;
12088
12089        final AttachInfo attachInfo = mAttachInfo;
12090        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12091        width = (int) ((width * scale) + 0.5f);
12092        height = (int) ((height * scale) + 0.5f);
12093
12094        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12095        if (bitmap == null) {
12096            throw new OutOfMemoryError();
12097        }
12098
12099        Resources resources = getResources();
12100        if (resources != null) {
12101            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12102        }
12103
12104        Canvas canvas;
12105        if (attachInfo != null) {
12106            canvas = attachInfo.mCanvas;
12107            if (canvas == null) {
12108                canvas = new Canvas();
12109            }
12110            canvas.setBitmap(bitmap);
12111            // Temporarily clobber the cached Canvas in case one of our children
12112            // is also using a drawing cache. Without this, the children would
12113            // steal the canvas by attaching their own bitmap to it and bad, bad
12114            // things would happen (invisible views, corrupted drawings, etc.)
12115            attachInfo.mCanvas = null;
12116        } else {
12117            // This case should hopefully never or seldom happen
12118            canvas = new Canvas(bitmap);
12119        }
12120
12121        if ((backgroundColor & 0xff000000) != 0) {
12122            bitmap.eraseColor(backgroundColor);
12123        }
12124
12125        computeScroll();
12126        final int restoreCount = canvas.save();
12127        canvas.scale(scale, scale);
12128        canvas.translate(-mScrollX, -mScrollY);
12129
12130        // Temporarily remove the dirty mask
12131        int flags = mPrivateFlags;
12132        mPrivateFlags &= ~DIRTY_MASK;
12133
12134        // Fast path for layouts with no backgrounds
12135        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12136            dispatchDraw(canvas);
12137        } else {
12138            draw(canvas);
12139        }
12140
12141        mPrivateFlags = flags;
12142
12143        canvas.restoreToCount(restoreCount);
12144        canvas.setBitmap(null);
12145
12146        if (attachInfo != null) {
12147            // Restore the cached Canvas for our siblings
12148            attachInfo.mCanvas = canvas;
12149        }
12150
12151        return bitmap;
12152    }
12153
12154    /**
12155     * Indicates whether this View is currently in edit mode. A View is usually
12156     * in edit mode when displayed within a developer tool. For instance, if
12157     * this View is being drawn by a visual user interface builder, this method
12158     * should return true.
12159     *
12160     * Subclasses should check the return value of this method to provide
12161     * different behaviors if their normal behavior might interfere with the
12162     * host environment. For instance: the class spawns a thread in its
12163     * constructor, the drawing code relies on device-specific features, etc.
12164     *
12165     * This method is usually checked in the drawing code of custom widgets.
12166     *
12167     * @return True if this View is in edit mode, false otherwise.
12168     */
12169    public boolean isInEditMode() {
12170        return false;
12171    }
12172
12173    /**
12174     * If the View draws content inside its padding and enables fading edges,
12175     * it needs to support padding offsets. Padding offsets are added to the
12176     * fading edges to extend the length of the fade so that it covers pixels
12177     * drawn inside the padding.
12178     *
12179     * Subclasses of this class should override this method if they need
12180     * to draw content inside the padding.
12181     *
12182     * @return True if padding offset must be applied, false otherwise.
12183     *
12184     * @see #getLeftPaddingOffset()
12185     * @see #getRightPaddingOffset()
12186     * @see #getTopPaddingOffset()
12187     * @see #getBottomPaddingOffset()
12188     *
12189     * @since CURRENT
12190     */
12191    protected boolean isPaddingOffsetRequired() {
12192        return false;
12193    }
12194
12195    /**
12196     * Amount by which to extend the left fading region. Called only when
12197     * {@link #isPaddingOffsetRequired()} returns true.
12198     *
12199     * @return The left padding offset in pixels.
12200     *
12201     * @see #isPaddingOffsetRequired()
12202     *
12203     * @since CURRENT
12204     */
12205    protected int getLeftPaddingOffset() {
12206        return 0;
12207    }
12208
12209    /**
12210     * Amount by which to extend the right fading region. Called only when
12211     * {@link #isPaddingOffsetRequired()} returns true.
12212     *
12213     * @return The right padding offset in pixels.
12214     *
12215     * @see #isPaddingOffsetRequired()
12216     *
12217     * @since CURRENT
12218     */
12219    protected int getRightPaddingOffset() {
12220        return 0;
12221    }
12222
12223    /**
12224     * Amount by which to extend the top fading region. Called only when
12225     * {@link #isPaddingOffsetRequired()} returns true.
12226     *
12227     * @return The top padding offset in pixels.
12228     *
12229     * @see #isPaddingOffsetRequired()
12230     *
12231     * @since CURRENT
12232     */
12233    protected int getTopPaddingOffset() {
12234        return 0;
12235    }
12236
12237    /**
12238     * Amount by which to extend the bottom fading region. Called only when
12239     * {@link #isPaddingOffsetRequired()} returns true.
12240     *
12241     * @return The bottom padding offset in pixels.
12242     *
12243     * @see #isPaddingOffsetRequired()
12244     *
12245     * @since CURRENT
12246     */
12247    protected int getBottomPaddingOffset() {
12248        return 0;
12249    }
12250
12251    /**
12252     * @hide
12253     * @param offsetRequired
12254     */
12255    protected int getFadeTop(boolean offsetRequired) {
12256        int top = mPaddingTop;
12257        if (offsetRequired) top += getTopPaddingOffset();
12258        return top;
12259    }
12260
12261    /**
12262     * @hide
12263     * @param offsetRequired
12264     */
12265    protected int getFadeHeight(boolean offsetRequired) {
12266        int padding = mPaddingTop;
12267        if (offsetRequired) padding += getTopPaddingOffset();
12268        return mBottom - mTop - mPaddingBottom - padding;
12269    }
12270
12271    /**
12272     * <p>Indicates whether this view is attached to a hardware accelerated
12273     * window or not.</p>
12274     *
12275     * <p>Even if this method returns true, it does not mean that every call
12276     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12277     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12278     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12279     * window is hardware accelerated,
12280     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12281     * return false, and this method will return true.</p>
12282     *
12283     * @return True if the view is attached to a window and the window is
12284     *         hardware accelerated; false in any other case.
12285     */
12286    public boolean isHardwareAccelerated() {
12287        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12288    }
12289
12290    /**
12291     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12292     * case of an active Animation being run on the view.
12293     */
12294    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12295            Animation a, boolean scalingRequired) {
12296        Transformation invalidationTransform;
12297        final int flags = parent.mGroupFlags;
12298        final boolean initialized = a.isInitialized();
12299        if (!initialized) {
12300            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
12301            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12302            onAnimationStart();
12303        }
12304
12305        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12306        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12307            if (parent.mInvalidationTransformation == null) {
12308                parent.mInvalidationTransformation = new Transformation();
12309            }
12310            invalidationTransform = parent.mInvalidationTransformation;
12311            a.getTransformation(drawingTime, invalidationTransform, 1f);
12312        } else {
12313            invalidationTransform = parent.mChildTransformation;
12314        }
12315        if (more) {
12316            if (!a.willChangeBounds()) {
12317                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12318                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12319                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12320                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12321                    // The child need to draw an animation, potentially offscreen, so
12322                    // make sure we do not cancel invalidate requests
12323                    parent.mPrivateFlags |= DRAW_ANIMATION;
12324                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12325                }
12326            } else {
12327                if (parent.mInvalidateRegion == null) {
12328                    parent.mInvalidateRegion = new RectF();
12329                }
12330                final RectF region = parent.mInvalidateRegion;
12331                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12332                        invalidationTransform);
12333
12334                // The child need to draw an animation, potentially offscreen, so
12335                // make sure we do not cancel invalidate requests
12336                parent.mPrivateFlags |= DRAW_ANIMATION;
12337
12338                final int left = mLeft + (int) region.left;
12339                final int top = mTop + (int) region.top;
12340                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12341                        top + (int) (region.height() + .5f));
12342            }
12343        }
12344        return more;
12345    }
12346
12347    void setDisplayListProperties() {
12348        setDisplayListProperties(mDisplayList);
12349    }
12350
12351    /**
12352     * This method is called by getDisplayList() when a display list is created or re-rendered.
12353     * It sets or resets the current value of all properties on that display list (resetting is
12354     * necessary when a display list is being re-created, because we need to make sure that
12355     * previously-set transform values
12356     */
12357    void setDisplayListProperties(DisplayList displayList) {
12358        if (USE_DISPLAY_LIST_PROPERTIES && displayList != null) {
12359            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12360            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12361            if (mParent instanceof ViewGroup) {
12362                displayList.setClipChildren(
12363                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12364            }
12365            float alpha = 1;
12366            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12367                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12368                ViewGroup parentVG = (ViewGroup) mParent;
12369                final boolean hasTransform =
12370                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12371                if (hasTransform) {
12372                    Transformation transform = parentVG.mChildTransformation;
12373                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12374                    if (transformType != Transformation.TYPE_IDENTITY) {
12375                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12376                            alpha = transform.getAlpha();
12377                        }
12378                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12379                            displayList.setStaticMatrix(transform.getMatrix());
12380                        }
12381                    }
12382                }
12383            }
12384            if (mTransformationInfo != null) {
12385                alpha *= mTransformationInfo.mAlpha;
12386                if (alpha < 1) {
12387                    final int multipliedAlpha = (int) (255 * alpha);
12388                    if (onSetAlpha(multipliedAlpha)) {
12389                        alpha = 1;
12390                    }
12391                }
12392                displayList.setTransformationInfo(alpha,
12393                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12394                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12395                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12396                        mTransformationInfo.mScaleY);
12397                if (mTransformationInfo.mCamera == null) {
12398                    mTransformationInfo.mCamera = new Camera();
12399                    mTransformationInfo.matrix3D = new Matrix();
12400                }
12401                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12402                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12403                    displayList.setPivotX(getPivotX());
12404                    displayList.setPivotY(getPivotY());
12405                }
12406            } else if (alpha < 1) {
12407                displayList.setAlpha(alpha);
12408            }
12409        }
12410    }
12411
12412    /**
12413     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12414     * This draw() method is an implementation detail and is not intended to be overridden or
12415     * to be called from anywhere else other than ViewGroup.drawChild().
12416     */
12417    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12418        boolean useDisplayListProperties = USE_DISPLAY_LIST_PROPERTIES && mAttachInfo != null &&
12419                mAttachInfo.mHardwareAccelerated;
12420        boolean more = false;
12421        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12422        final int flags = parent.mGroupFlags;
12423
12424        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12425            parent.mChildTransformation.clear();
12426            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12427        }
12428
12429        Transformation transformToApply = null;
12430        boolean concatMatrix = false;
12431
12432        boolean scalingRequired = false;
12433        boolean caching;
12434        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12435
12436        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12437        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12438                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12439            caching = true;
12440            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12441            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12442        } else {
12443            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12444        }
12445
12446        final Animation a = getAnimation();
12447        if (a != null) {
12448            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12449            concatMatrix = a.willChangeTransformationMatrix();
12450            transformToApply = parent.mChildTransformation;
12451        } else if (!useDisplayListProperties &&
12452                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12453            final boolean hasTransform =
12454                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
12455            if (hasTransform) {
12456                final int transformType = parent.mChildTransformation.getTransformationType();
12457                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12458                        parent.mChildTransformation : null;
12459                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12460            }
12461        }
12462
12463        concatMatrix |= !childHasIdentityMatrix;
12464
12465        // Sets the flag as early as possible to allow draw() implementations
12466        // to call invalidate() successfully when doing animations
12467        mPrivateFlags |= DRAWN;
12468
12469        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12470                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12471            return more;
12472        }
12473
12474        if (hardwareAccelerated) {
12475            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12476            // retain the flag's value temporarily in the mRecreateDisplayList flag
12477            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12478            mPrivateFlags &= ~INVALIDATED;
12479        }
12480
12481        computeScroll();
12482
12483        final int sx = mScrollX;
12484        final int sy = mScrollY;
12485
12486        DisplayList displayList = null;
12487        Bitmap cache = null;
12488        boolean hasDisplayList = false;
12489        if (caching) {
12490            if (!hardwareAccelerated) {
12491                if (layerType != LAYER_TYPE_NONE) {
12492                    layerType = LAYER_TYPE_SOFTWARE;
12493                    buildDrawingCache(true);
12494                }
12495                cache = getDrawingCache(true);
12496            } else {
12497                switch (layerType) {
12498                    case LAYER_TYPE_SOFTWARE:
12499                        if (useDisplayListProperties) {
12500                            hasDisplayList = canHaveDisplayList();
12501                        } else {
12502                            buildDrawingCache(true);
12503                            cache = getDrawingCache(true);
12504                        }
12505                        break;
12506                    case LAYER_TYPE_HARDWARE:
12507                        if (useDisplayListProperties) {
12508                            hasDisplayList = canHaveDisplayList();
12509                        }
12510                        break;
12511                    case LAYER_TYPE_NONE:
12512                        // Delay getting the display list until animation-driven alpha values are
12513                        // set up and possibly passed on to the view
12514                        hasDisplayList = canHaveDisplayList();
12515                        break;
12516                }
12517            }
12518        }
12519        useDisplayListProperties &= hasDisplayList;
12520        if (useDisplayListProperties) {
12521            displayList = getDisplayList();
12522            if (!displayList.isValid()) {
12523                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12524                // to getDisplayList(), the display list will be marked invalid and we should not
12525                // try to use it again.
12526                displayList = null;
12527                hasDisplayList = false;
12528                useDisplayListProperties = false;
12529            }
12530        }
12531
12532        final boolean hasNoCache = cache == null || hasDisplayList;
12533        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12534                layerType != LAYER_TYPE_HARDWARE;
12535
12536        int restoreTo = -1;
12537        if (!useDisplayListProperties || transformToApply != null) {
12538            restoreTo = canvas.save();
12539        }
12540        if (offsetForScroll) {
12541            canvas.translate(mLeft - sx, mTop - sy);
12542        } else {
12543            if (!useDisplayListProperties) {
12544                canvas.translate(mLeft, mTop);
12545            }
12546            if (scalingRequired) {
12547                if (useDisplayListProperties) {
12548                    // TODO: Might not need this if we put everything inside the DL
12549                    restoreTo = canvas.save();
12550                }
12551                // mAttachInfo cannot be null, otherwise scalingRequired == false
12552                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12553                canvas.scale(scale, scale);
12554            }
12555        }
12556
12557        float alpha = useDisplayListProperties ? 1 : getAlpha();
12558        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12559            if (transformToApply != null || !childHasIdentityMatrix) {
12560                int transX = 0;
12561                int transY = 0;
12562
12563                if (offsetForScroll) {
12564                    transX = -sx;
12565                    transY = -sy;
12566                }
12567
12568                if (transformToApply != null) {
12569                    if (concatMatrix) {
12570                        if (useDisplayListProperties) {
12571                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12572                        } else {
12573                            // Undo the scroll translation, apply the transformation matrix,
12574                            // then redo the scroll translate to get the correct result.
12575                            canvas.translate(-transX, -transY);
12576                            canvas.concat(transformToApply.getMatrix());
12577                            canvas.translate(transX, transY);
12578                        }
12579                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12580                    }
12581
12582                    float transformAlpha = transformToApply.getAlpha();
12583                    if (transformAlpha < 1) {
12584                        alpha *= transformToApply.getAlpha();
12585                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12586                    }
12587                }
12588
12589                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12590                    canvas.translate(-transX, -transY);
12591                    canvas.concat(getMatrix());
12592                    canvas.translate(transX, transY);
12593                }
12594            }
12595
12596            if (alpha < 1) {
12597                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12598                if (hasNoCache) {
12599                    final int multipliedAlpha = (int) (255 * alpha);
12600                    if (!onSetAlpha(multipliedAlpha)) {
12601                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12602                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12603                                layerType != LAYER_TYPE_NONE) {
12604                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12605                        }
12606                        if (useDisplayListProperties) {
12607                            displayList.setAlpha(alpha * getAlpha());
12608                        } else  if (layerType == LAYER_TYPE_NONE) {
12609                            final int scrollX = hasDisplayList ? 0 : sx;
12610                            final int scrollY = hasDisplayList ? 0 : sy;
12611                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12612                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12613                        }
12614                    } else {
12615                        // Alpha is handled by the child directly, clobber the layer's alpha
12616                        mPrivateFlags |= ALPHA_SET;
12617                    }
12618                }
12619            }
12620        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12621            onSetAlpha(255);
12622            mPrivateFlags &= ~ALPHA_SET;
12623        }
12624
12625        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12626                !useDisplayListProperties) {
12627            if (offsetForScroll) {
12628                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12629            } else {
12630                if (!scalingRequired || cache == null) {
12631                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12632                } else {
12633                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12634                }
12635            }
12636        }
12637
12638        if (!useDisplayListProperties && hasDisplayList) {
12639            displayList = getDisplayList();
12640            if (!displayList.isValid()) {
12641                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12642                // to getDisplayList(), the display list will be marked invalid and we should not
12643                // try to use it again.
12644                displayList = null;
12645                hasDisplayList = false;
12646            }
12647        }
12648
12649        if (hasNoCache) {
12650            boolean layerRendered = false;
12651            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12652                final HardwareLayer layer = getHardwareLayer();
12653                if (layer != null && layer.isValid()) {
12654                    mLayerPaint.setAlpha((int) (alpha * 255));
12655                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12656                    layerRendered = true;
12657                } else {
12658                    final int scrollX = hasDisplayList ? 0 : sx;
12659                    final int scrollY = hasDisplayList ? 0 : sy;
12660                    canvas.saveLayer(scrollX, scrollY,
12661                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12662                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12663                }
12664            }
12665
12666            if (!layerRendered) {
12667                if (!hasDisplayList) {
12668                    // Fast path for layouts with no backgrounds
12669                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12670                        if (ViewDebug.TRACE_HIERARCHY) {
12671                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12672                        }
12673                        mPrivateFlags &= ~DIRTY_MASK;
12674                        dispatchDraw(canvas);
12675                    } else {
12676                        draw(canvas);
12677                    }
12678                } else {
12679                    mPrivateFlags &= ~DIRTY_MASK;
12680                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
12681                            mRight - mLeft, mBottom - mTop, null, flags);
12682                }
12683            }
12684        } else if (cache != null) {
12685            mPrivateFlags &= ~DIRTY_MASK;
12686            Paint cachePaint;
12687
12688            if (layerType == LAYER_TYPE_NONE) {
12689                cachePaint = parent.mCachePaint;
12690                if (cachePaint == null) {
12691                    cachePaint = new Paint();
12692                    cachePaint.setDither(false);
12693                    parent.mCachePaint = cachePaint;
12694                }
12695                if (alpha < 1) {
12696                    cachePaint.setAlpha((int) (alpha * 255));
12697                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12698                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
12699                    cachePaint.setAlpha(255);
12700                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12701                }
12702            } else {
12703                cachePaint = mLayerPaint;
12704                cachePaint.setAlpha((int) (alpha * 255));
12705            }
12706            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
12707        }
12708
12709        if (restoreTo >= 0) {
12710            canvas.restoreToCount(restoreTo);
12711        }
12712
12713        if (a != null && !more) {
12714            if (!hardwareAccelerated && !a.getFillAfter()) {
12715                onSetAlpha(255);
12716            }
12717            parent.finishAnimatingView(this, a);
12718        }
12719
12720        if (more && hardwareAccelerated) {
12721            // invalidation is the trigger to recreate display lists, so if we're using
12722            // display lists to render, force an invalidate to allow the animation to
12723            // continue drawing another frame
12724            parent.invalidate(true);
12725            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12726                // alpha animations should cause the child to recreate its display list
12727                invalidate(true);
12728            }
12729        }
12730
12731        mRecreateDisplayList = false;
12732
12733        return more;
12734    }
12735
12736    /**
12737     * Manually render this view (and all of its children) to the given Canvas.
12738     * The view must have already done a full layout before this function is
12739     * called.  When implementing a view, implement
12740     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
12741     * If you do need to override this method, call the superclass version.
12742     *
12743     * @param canvas The Canvas to which the View is rendered.
12744     */
12745    public void draw(Canvas canvas) {
12746        if (ViewDebug.TRACE_HIERARCHY) {
12747            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12748        }
12749
12750        final int privateFlags = mPrivateFlags;
12751        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
12752                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
12753        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
12754
12755        /*
12756         * Draw traversal performs several drawing steps which must be executed
12757         * in the appropriate order:
12758         *
12759         *      1. Draw the background
12760         *      2. If necessary, save the canvas' layers to prepare for fading
12761         *      3. Draw view's content
12762         *      4. Draw children
12763         *      5. If necessary, draw the fading edges and restore layers
12764         *      6. Draw decorations (scrollbars for instance)
12765         */
12766
12767        // Step 1, draw the background, if needed
12768        int saveCount;
12769
12770        if (!dirtyOpaque) {
12771            final Drawable background = mBackground;
12772            if (background != null) {
12773                final int scrollX = mScrollX;
12774                final int scrollY = mScrollY;
12775
12776                if (mBackgroundSizeChanged) {
12777                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
12778                    mBackgroundSizeChanged = false;
12779                }
12780
12781                if ((scrollX | scrollY) == 0) {
12782                    background.draw(canvas);
12783                } else {
12784                    canvas.translate(scrollX, scrollY);
12785                    background.draw(canvas);
12786                    canvas.translate(-scrollX, -scrollY);
12787                }
12788            }
12789        }
12790
12791        // skip step 2 & 5 if possible (common case)
12792        final int viewFlags = mViewFlags;
12793        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
12794        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
12795        if (!verticalEdges && !horizontalEdges) {
12796            // Step 3, draw the content
12797            if (!dirtyOpaque) onDraw(canvas);
12798
12799            // Step 4, draw the children
12800            dispatchDraw(canvas);
12801
12802            // Step 6, draw decorations (scrollbars)
12803            onDrawScrollBars(canvas);
12804
12805            // we're done...
12806            return;
12807        }
12808
12809        /*
12810         * Here we do the full fledged routine...
12811         * (this is an uncommon case where speed matters less,
12812         * this is why we repeat some of the tests that have been
12813         * done above)
12814         */
12815
12816        boolean drawTop = false;
12817        boolean drawBottom = false;
12818        boolean drawLeft = false;
12819        boolean drawRight = false;
12820
12821        float topFadeStrength = 0.0f;
12822        float bottomFadeStrength = 0.0f;
12823        float leftFadeStrength = 0.0f;
12824        float rightFadeStrength = 0.0f;
12825
12826        // Step 2, save the canvas' layers
12827        int paddingLeft = mPaddingLeft;
12828
12829        final boolean offsetRequired = isPaddingOffsetRequired();
12830        if (offsetRequired) {
12831            paddingLeft += getLeftPaddingOffset();
12832        }
12833
12834        int left = mScrollX + paddingLeft;
12835        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
12836        int top = mScrollY + getFadeTop(offsetRequired);
12837        int bottom = top + getFadeHeight(offsetRequired);
12838
12839        if (offsetRequired) {
12840            right += getRightPaddingOffset();
12841            bottom += getBottomPaddingOffset();
12842        }
12843
12844        final ScrollabilityCache scrollabilityCache = mScrollCache;
12845        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
12846        int length = (int) fadeHeight;
12847
12848        // clip the fade length if top and bottom fades overlap
12849        // overlapping fades produce odd-looking artifacts
12850        if (verticalEdges && (top + length > bottom - length)) {
12851            length = (bottom - top) / 2;
12852        }
12853
12854        // also clip horizontal fades if necessary
12855        if (horizontalEdges && (left + length > right - length)) {
12856            length = (right - left) / 2;
12857        }
12858
12859        if (verticalEdges) {
12860            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
12861            drawTop = topFadeStrength * fadeHeight > 1.0f;
12862            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
12863            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
12864        }
12865
12866        if (horizontalEdges) {
12867            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
12868            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
12869            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
12870            drawRight = rightFadeStrength * fadeHeight > 1.0f;
12871        }
12872
12873        saveCount = canvas.getSaveCount();
12874
12875        int solidColor = getSolidColor();
12876        if (solidColor == 0) {
12877            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12878
12879            if (drawTop) {
12880                canvas.saveLayer(left, top, right, top + length, null, flags);
12881            }
12882
12883            if (drawBottom) {
12884                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
12885            }
12886
12887            if (drawLeft) {
12888                canvas.saveLayer(left, top, left + length, bottom, null, flags);
12889            }
12890
12891            if (drawRight) {
12892                canvas.saveLayer(right - length, top, right, bottom, null, flags);
12893            }
12894        } else {
12895            scrollabilityCache.setFadeColor(solidColor);
12896        }
12897
12898        // Step 3, draw the content
12899        if (!dirtyOpaque) onDraw(canvas);
12900
12901        // Step 4, draw the children
12902        dispatchDraw(canvas);
12903
12904        // Step 5, draw the fade effect and restore layers
12905        final Paint p = scrollabilityCache.paint;
12906        final Matrix matrix = scrollabilityCache.matrix;
12907        final Shader fade = scrollabilityCache.shader;
12908
12909        if (drawTop) {
12910            matrix.setScale(1, fadeHeight * topFadeStrength);
12911            matrix.postTranslate(left, top);
12912            fade.setLocalMatrix(matrix);
12913            canvas.drawRect(left, top, right, top + length, p);
12914        }
12915
12916        if (drawBottom) {
12917            matrix.setScale(1, fadeHeight * bottomFadeStrength);
12918            matrix.postRotate(180);
12919            matrix.postTranslate(left, bottom);
12920            fade.setLocalMatrix(matrix);
12921            canvas.drawRect(left, bottom - length, right, bottom, p);
12922        }
12923
12924        if (drawLeft) {
12925            matrix.setScale(1, fadeHeight * leftFadeStrength);
12926            matrix.postRotate(-90);
12927            matrix.postTranslate(left, top);
12928            fade.setLocalMatrix(matrix);
12929            canvas.drawRect(left, top, left + length, bottom, p);
12930        }
12931
12932        if (drawRight) {
12933            matrix.setScale(1, fadeHeight * rightFadeStrength);
12934            matrix.postRotate(90);
12935            matrix.postTranslate(right, top);
12936            fade.setLocalMatrix(matrix);
12937            canvas.drawRect(right - length, top, right, bottom, p);
12938        }
12939
12940        canvas.restoreToCount(saveCount);
12941
12942        // Step 6, draw decorations (scrollbars)
12943        onDrawScrollBars(canvas);
12944    }
12945
12946    /**
12947     * Override this if your view is known to always be drawn on top of a solid color background,
12948     * and needs to draw fading edges. Returning a non-zero color enables the view system to
12949     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
12950     * should be set to 0xFF.
12951     *
12952     * @see #setVerticalFadingEdgeEnabled(boolean)
12953     * @see #setHorizontalFadingEdgeEnabled(boolean)
12954     *
12955     * @return The known solid color background for this view, or 0 if the color may vary
12956     */
12957    @ViewDebug.ExportedProperty(category = "drawing")
12958    public int getSolidColor() {
12959        return 0;
12960    }
12961
12962    /**
12963     * Build a human readable string representation of the specified view flags.
12964     *
12965     * @param flags the view flags to convert to a string
12966     * @return a String representing the supplied flags
12967     */
12968    private static String printFlags(int flags) {
12969        String output = "";
12970        int numFlags = 0;
12971        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
12972            output += "TAKES_FOCUS";
12973            numFlags++;
12974        }
12975
12976        switch (flags & VISIBILITY_MASK) {
12977        case INVISIBLE:
12978            if (numFlags > 0) {
12979                output += " ";
12980            }
12981            output += "INVISIBLE";
12982            // USELESS HERE numFlags++;
12983            break;
12984        case GONE:
12985            if (numFlags > 0) {
12986                output += " ";
12987            }
12988            output += "GONE";
12989            // USELESS HERE numFlags++;
12990            break;
12991        default:
12992            break;
12993        }
12994        return output;
12995    }
12996
12997    /**
12998     * Build a human readable string representation of the specified private
12999     * view flags.
13000     *
13001     * @param privateFlags the private view flags to convert to a string
13002     * @return a String representing the supplied flags
13003     */
13004    private static String printPrivateFlags(int privateFlags) {
13005        String output = "";
13006        int numFlags = 0;
13007
13008        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13009            output += "WANTS_FOCUS";
13010            numFlags++;
13011        }
13012
13013        if ((privateFlags & FOCUSED) == FOCUSED) {
13014            if (numFlags > 0) {
13015                output += " ";
13016            }
13017            output += "FOCUSED";
13018            numFlags++;
13019        }
13020
13021        if ((privateFlags & SELECTED) == SELECTED) {
13022            if (numFlags > 0) {
13023                output += " ";
13024            }
13025            output += "SELECTED";
13026            numFlags++;
13027        }
13028
13029        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13030            if (numFlags > 0) {
13031                output += " ";
13032            }
13033            output += "IS_ROOT_NAMESPACE";
13034            numFlags++;
13035        }
13036
13037        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13038            if (numFlags > 0) {
13039                output += " ";
13040            }
13041            output += "HAS_BOUNDS";
13042            numFlags++;
13043        }
13044
13045        if ((privateFlags & DRAWN) == DRAWN) {
13046            if (numFlags > 0) {
13047                output += " ";
13048            }
13049            output += "DRAWN";
13050            // USELESS HERE numFlags++;
13051        }
13052        return output;
13053    }
13054
13055    /**
13056     * <p>Indicates whether or not this view's layout will be requested during
13057     * the next hierarchy layout pass.</p>
13058     *
13059     * @return true if the layout will be forced during next layout pass
13060     */
13061    public boolean isLayoutRequested() {
13062        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13063    }
13064
13065    /**
13066     * Assign a size and position to a view and all of its
13067     * descendants
13068     *
13069     * <p>This is the second phase of the layout mechanism.
13070     * (The first is measuring). In this phase, each parent calls
13071     * layout on all of its children to position them.
13072     * This is typically done using the child measurements
13073     * that were stored in the measure pass().</p>
13074     *
13075     * <p>Derived classes should not override this method.
13076     * Derived classes with children should override
13077     * onLayout. In that method, they should
13078     * call layout on each of their children.</p>
13079     *
13080     * @param l Left position, relative to parent
13081     * @param t Top position, relative to parent
13082     * @param r Right position, relative to parent
13083     * @param b Bottom position, relative to parent
13084     */
13085    @SuppressWarnings({"unchecked"})
13086    public void layout(int l, int t, int r, int b) {
13087        int oldL = mLeft;
13088        int oldT = mTop;
13089        int oldB = mBottom;
13090        int oldR = mRight;
13091        boolean changed = setFrame(l, t, r, b);
13092        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13093            if (ViewDebug.TRACE_HIERARCHY) {
13094                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13095            }
13096
13097            onLayout(changed, l, t, r, b);
13098            mPrivateFlags &= ~LAYOUT_REQUIRED;
13099
13100            ListenerInfo li = mListenerInfo;
13101            if (li != null && li.mOnLayoutChangeListeners != null) {
13102                ArrayList<OnLayoutChangeListener> listenersCopy =
13103                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13104                int numListeners = listenersCopy.size();
13105                for (int i = 0; i < numListeners; ++i) {
13106                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13107                }
13108            }
13109        }
13110        mPrivateFlags &= ~FORCE_LAYOUT;
13111    }
13112
13113    /**
13114     * Called from layout when this view should
13115     * assign a size and position to each of its children.
13116     *
13117     * Derived classes with children should override
13118     * this method and call layout on each of
13119     * their children.
13120     * @param changed This is a new size or position for this view
13121     * @param left Left position, relative to parent
13122     * @param top Top position, relative to parent
13123     * @param right Right position, relative to parent
13124     * @param bottom Bottom position, relative to parent
13125     */
13126    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13127    }
13128
13129    /**
13130     * Assign a size and position to this view.
13131     *
13132     * This is called from layout.
13133     *
13134     * @param left Left position, relative to parent
13135     * @param top Top position, relative to parent
13136     * @param right Right position, relative to parent
13137     * @param bottom Bottom position, relative to parent
13138     * @return true if the new size and position are different than the
13139     *         previous ones
13140     * {@hide}
13141     */
13142    protected boolean setFrame(int left, int top, int right, int bottom) {
13143        boolean changed = false;
13144
13145        if (DBG) {
13146            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13147                    + right + "," + bottom + ")");
13148        }
13149
13150        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13151            changed = true;
13152
13153            // Remember our drawn bit
13154            int drawn = mPrivateFlags & DRAWN;
13155
13156            int oldWidth = mRight - mLeft;
13157            int oldHeight = mBottom - mTop;
13158            int newWidth = right - left;
13159            int newHeight = bottom - top;
13160            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13161
13162            // Invalidate our old position
13163            invalidate(sizeChanged);
13164
13165            mLeft = left;
13166            mTop = top;
13167            mRight = right;
13168            mBottom = bottom;
13169            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
13170                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13171            }
13172
13173            mPrivateFlags |= HAS_BOUNDS;
13174
13175
13176            if (sizeChanged) {
13177                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13178                    // A change in dimension means an auto-centered pivot point changes, too
13179                    if (mTransformationInfo != null) {
13180                        mTransformationInfo.mMatrixDirty = true;
13181                    }
13182                }
13183                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13184            }
13185
13186            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13187                // If we are visible, force the DRAWN bit to on so that
13188                // this invalidate will go through (at least to our parent).
13189                // This is because someone may have invalidated this view
13190                // before this call to setFrame came in, thereby clearing
13191                // the DRAWN bit.
13192                mPrivateFlags |= DRAWN;
13193                invalidate(sizeChanged);
13194                // parent display list may need to be recreated based on a change in the bounds
13195                // of any child
13196                invalidateParentCaches();
13197            }
13198
13199            // Reset drawn bit to original value (invalidate turns it off)
13200            mPrivateFlags |= drawn;
13201
13202            mBackgroundSizeChanged = true;
13203        }
13204        return changed;
13205    }
13206
13207    /**
13208     * Finalize inflating a view from XML.  This is called as the last phase
13209     * of inflation, after all child views have been added.
13210     *
13211     * <p>Even if the subclass overrides onFinishInflate, they should always be
13212     * sure to call the super method, so that we get called.
13213     */
13214    protected void onFinishInflate() {
13215    }
13216
13217    /**
13218     * Returns the resources associated with this view.
13219     *
13220     * @return Resources object.
13221     */
13222    public Resources getResources() {
13223        return mResources;
13224    }
13225
13226    /**
13227     * Invalidates the specified Drawable.
13228     *
13229     * @param drawable the drawable to invalidate
13230     */
13231    public void invalidateDrawable(Drawable drawable) {
13232        if (verifyDrawable(drawable)) {
13233            final Rect dirty = drawable.getBounds();
13234            final int scrollX = mScrollX;
13235            final int scrollY = mScrollY;
13236
13237            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13238                    dirty.right + scrollX, dirty.bottom + scrollY);
13239        }
13240    }
13241
13242    /**
13243     * Schedules an action on a drawable to occur at a specified time.
13244     *
13245     * @param who the recipient of the action
13246     * @param what the action to run on the drawable
13247     * @param when the time at which the action must occur. Uses the
13248     *        {@link SystemClock#uptimeMillis} timebase.
13249     */
13250    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13251        if (verifyDrawable(who) && what != null) {
13252            final long delay = when - SystemClock.uptimeMillis();
13253            if (mAttachInfo != null) {
13254                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13255                        Choreographer.CALLBACK_ANIMATION, what, who,
13256                        Choreographer.subtractFrameDelay(delay));
13257            } else {
13258                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13259            }
13260        }
13261    }
13262
13263    /**
13264     * Cancels a scheduled action on a drawable.
13265     *
13266     * @param who the recipient of the action
13267     * @param what the action to cancel
13268     */
13269    public void unscheduleDrawable(Drawable who, Runnable what) {
13270        if (verifyDrawable(who) && what != null) {
13271            if (mAttachInfo != null) {
13272                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13273                        Choreographer.CALLBACK_ANIMATION, what, who);
13274            } else {
13275                ViewRootImpl.getRunQueue().removeCallbacks(what);
13276            }
13277        }
13278    }
13279
13280    /**
13281     * Unschedule any events associated with the given Drawable.  This can be
13282     * used when selecting a new Drawable into a view, so that the previous
13283     * one is completely unscheduled.
13284     *
13285     * @param who The Drawable to unschedule.
13286     *
13287     * @see #drawableStateChanged
13288     */
13289    public void unscheduleDrawable(Drawable who) {
13290        if (mAttachInfo != null && who != null) {
13291            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13292                    Choreographer.CALLBACK_ANIMATION, null, who);
13293        }
13294    }
13295
13296    /**
13297    * Return the layout direction of a given Drawable.
13298    *
13299    * @param who the Drawable to query
13300    */
13301    public int getResolvedLayoutDirection(Drawable who) {
13302        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13303    }
13304
13305    /**
13306     * If your view subclass is displaying its own Drawable objects, it should
13307     * override this function and return true for any Drawable it is
13308     * displaying.  This allows animations for those drawables to be
13309     * scheduled.
13310     *
13311     * <p>Be sure to call through to the super class when overriding this
13312     * function.
13313     *
13314     * @param who The Drawable to verify.  Return true if it is one you are
13315     *            displaying, else return the result of calling through to the
13316     *            super class.
13317     *
13318     * @return boolean If true than the Drawable is being displayed in the
13319     *         view; else false and it is not allowed to animate.
13320     *
13321     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13322     * @see #drawableStateChanged()
13323     */
13324    protected boolean verifyDrawable(Drawable who) {
13325        return who == mBackground;
13326    }
13327
13328    /**
13329     * This function is called whenever the state of the view changes in such
13330     * a way that it impacts the state of drawables being shown.
13331     *
13332     * <p>Be sure to call through to the superclass when overriding this
13333     * function.
13334     *
13335     * @see Drawable#setState(int[])
13336     */
13337    protected void drawableStateChanged() {
13338        Drawable d = mBackground;
13339        if (d != null && d.isStateful()) {
13340            d.setState(getDrawableState());
13341        }
13342    }
13343
13344    /**
13345     * Call this to force a view to update its drawable state. This will cause
13346     * drawableStateChanged to be called on this view. Views that are interested
13347     * in the new state should call getDrawableState.
13348     *
13349     * @see #drawableStateChanged
13350     * @see #getDrawableState
13351     */
13352    public void refreshDrawableState() {
13353        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13354        drawableStateChanged();
13355
13356        ViewParent parent = mParent;
13357        if (parent != null) {
13358            parent.childDrawableStateChanged(this);
13359        }
13360    }
13361
13362    /**
13363     * Return an array of resource IDs of the drawable states representing the
13364     * current state of the view.
13365     *
13366     * @return The current drawable state
13367     *
13368     * @see Drawable#setState(int[])
13369     * @see #drawableStateChanged()
13370     * @see #onCreateDrawableState(int)
13371     */
13372    public final int[] getDrawableState() {
13373        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13374            return mDrawableState;
13375        } else {
13376            mDrawableState = onCreateDrawableState(0);
13377            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13378            return mDrawableState;
13379        }
13380    }
13381
13382    /**
13383     * Generate the new {@link android.graphics.drawable.Drawable} state for
13384     * this view. This is called by the view
13385     * system when the cached Drawable state is determined to be invalid.  To
13386     * retrieve the current state, you should use {@link #getDrawableState}.
13387     *
13388     * @param extraSpace if non-zero, this is the number of extra entries you
13389     * would like in the returned array in which you can place your own
13390     * states.
13391     *
13392     * @return Returns an array holding the current {@link Drawable} state of
13393     * the view.
13394     *
13395     * @see #mergeDrawableStates(int[], int[])
13396     */
13397    protected int[] onCreateDrawableState(int extraSpace) {
13398        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13399                mParent instanceof View) {
13400            return ((View) mParent).onCreateDrawableState(extraSpace);
13401        }
13402
13403        int[] drawableState;
13404
13405        int privateFlags = mPrivateFlags;
13406
13407        int viewStateIndex = 0;
13408        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13409        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13410        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13411        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13412        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13413        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13414        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13415                HardwareRenderer.isAvailable()) {
13416            // This is set if HW acceleration is requested, even if the current
13417            // process doesn't allow it.  This is just to allow app preview
13418            // windows to better match their app.
13419            viewStateIndex |= VIEW_STATE_ACCELERATED;
13420        }
13421        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13422
13423        final int privateFlags2 = mPrivateFlags2;
13424        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13425        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13426
13427        drawableState = VIEW_STATE_SETS[viewStateIndex];
13428
13429        //noinspection ConstantIfStatement
13430        if (false) {
13431            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13432            Log.i("View", toString()
13433                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13434                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13435                    + " fo=" + hasFocus()
13436                    + " sl=" + ((privateFlags & SELECTED) != 0)
13437                    + " wf=" + hasWindowFocus()
13438                    + ": " + Arrays.toString(drawableState));
13439        }
13440
13441        if (extraSpace == 0) {
13442            return drawableState;
13443        }
13444
13445        final int[] fullState;
13446        if (drawableState != null) {
13447            fullState = new int[drawableState.length + extraSpace];
13448            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13449        } else {
13450            fullState = new int[extraSpace];
13451        }
13452
13453        return fullState;
13454    }
13455
13456    /**
13457     * Merge your own state values in <var>additionalState</var> into the base
13458     * state values <var>baseState</var> that were returned by
13459     * {@link #onCreateDrawableState(int)}.
13460     *
13461     * @param baseState The base state values returned by
13462     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13463     * own additional state values.
13464     *
13465     * @param additionalState The additional state values you would like
13466     * added to <var>baseState</var>; this array is not modified.
13467     *
13468     * @return As a convenience, the <var>baseState</var> array you originally
13469     * passed into the function is returned.
13470     *
13471     * @see #onCreateDrawableState(int)
13472     */
13473    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13474        final int N = baseState.length;
13475        int i = N - 1;
13476        while (i >= 0 && baseState[i] == 0) {
13477            i--;
13478        }
13479        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13480        return baseState;
13481    }
13482
13483    /**
13484     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13485     * on all Drawable objects associated with this view.
13486     */
13487    public void jumpDrawablesToCurrentState() {
13488        if (mBackground != null) {
13489            mBackground.jumpToCurrentState();
13490        }
13491    }
13492
13493    /**
13494     * Sets the background color for this view.
13495     * @param color the color of the background
13496     */
13497    @RemotableViewMethod
13498    public void setBackgroundColor(int color) {
13499        if (mBackground instanceof ColorDrawable) {
13500            ((ColorDrawable) mBackground).setColor(color);
13501        } else {
13502            setBackground(new ColorDrawable(color));
13503        }
13504    }
13505
13506    /**
13507     * Set the background to a given resource. The resource should refer to
13508     * a Drawable object or 0 to remove the background.
13509     * @param resid The identifier of the resource.
13510     *
13511     * @attr ref android.R.styleable#View_background
13512     */
13513    @RemotableViewMethod
13514    public void setBackgroundResource(int resid) {
13515        if (resid != 0 && resid == mBackgroundResource) {
13516            return;
13517        }
13518
13519        Drawable d= null;
13520        if (resid != 0) {
13521            d = mResources.getDrawable(resid);
13522        }
13523        setBackground(d);
13524
13525        mBackgroundResource = resid;
13526    }
13527
13528    /**
13529     * Set the background to a given Drawable, or remove the background. If the
13530     * background has padding, this View's padding is set to the background's
13531     * padding. However, when a background is removed, this View's padding isn't
13532     * touched. If setting the padding is desired, please use
13533     * {@link #setPadding(int, int, int, int)}.
13534     *
13535     * @param background The Drawable to use as the background, or null to remove the
13536     *        background
13537     */
13538    public void setBackground(Drawable background) {
13539        //noinspection deprecation
13540        setBackgroundDrawable(background);
13541    }
13542
13543    /**
13544     * @deprecated use {@link #setBackground(Drawable)} instead
13545     */
13546    @Deprecated
13547    public void setBackgroundDrawable(Drawable background) {
13548        if (background == mBackground) {
13549            return;
13550        }
13551
13552        boolean requestLayout = false;
13553
13554        mBackgroundResource = 0;
13555
13556        /*
13557         * Regardless of whether we're setting a new background or not, we want
13558         * to clear the previous drawable.
13559         */
13560        if (mBackground != null) {
13561            mBackground.setCallback(null);
13562            unscheduleDrawable(mBackground);
13563        }
13564
13565        if (background != null) {
13566            Rect padding = sThreadLocal.get();
13567            if (padding == null) {
13568                padding = new Rect();
13569                sThreadLocal.set(padding);
13570            }
13571            if (background.getPadding(padding)) {
13572                switch (background.getResolvedLayoutDirectionSelf()) {
13573                    case LAYOUT_DIRECTION_RTL:
13574                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13575                        break;
13576                    case LAYOUT_DIRECTION_LTR:
13577                    default:
13578                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13579                }
13580            }
13581
13582            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13583            // if it has a different minimum size, we should layout again
13584            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13585                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13586                requestLayout = true;
13587            }
13588
13589            background.setCallback(this);
13590            if (background.isStateful()) {
13591                background.setState(getDrawableState());
13592            }
13593            background.setVisible(getVisibility() == VISIBLE, false);
13594            mBackground = background;
13595
13596            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13597                mPrivateFlags &= ~SKIP_DRAW;
13598                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13599                requestLayout = true;
13600            }
13601        } else {
13602            /* Remove the background */
13603            mBackground = null;
13604
13605            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13606                /*
13607                 * This view ONLY drew the background before and we're removing
13608                 * the background, so now it won't draw anything
13609                 * (hence we SKIP_DRAW)
13610                 */
13611                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13612                mPrivateFlags |= SKIP_DRAW;
13613            }
13614
13615            /*
13616             * When the background is set, we try to apply its padding to this
13617             * View. When the background is removed, we don't touch this View's
13618             * padding. This is noted in the Javadocs. Hence, we don't need to
13619             * requestLayout(), the invalidate() below is sufficient.
13620             */
13621
13622            // The old background's minimum size could have affected this
13623            // View's layout, so let's requestLayout
13624            requestLayout = true;
13625        }
13626
13627        computeOpaqueFlags();
13628
13629        if (requestLayout) {
13630            requestLayout();
13631        }
13632
13633        mBackgroundSizeChanged = true;
13634        invalidate(true);
13635    }
13636
13637    /**
13638     * Gets the background drawable
13639     *
13640     * @return The drawable used as the background for this view, if any.
13641     *
13642     * @see #setBackground(Drawable)
13643     *
13644     * @attr ref android.R.styleable#View_background
13645     */
13646    public Drawable getBackground() {
13647        return mBackground;
13648    }
13649
13650    /**
13651     * Sets the padding. The view may add on the space required to display
13652     * the scrollbars, depending on the style and visibility of the scrollbars.
13653     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13654     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13655     * from the values set in this call.
13656     *
13657     * @attr ref android.R.styleable#View_padding
13658     * @attr ref android.R.styleable#View_paddingBottom
13659     * @attr ref android.R.styleable#View_paddingLeft
13660     * @attr ref android.R.styleable#View_paddingRight
13661     * @attr ref android.R.styleable#View_paddingTop
13662     * @param left the left padding in pixels
13663     * @param top the top padding in pixels
13664     * @param right the right padding in pixels
13665     * @param bottom the bottom padding in pixels
13666     */
13667    public void setPadding(int left, int top, int right, int bottom) {
13668        mUserPaddingStart = -1;
13669        mUserPaddingEnd = -1;
13670        mUserPaddingRelative = false;
13671
13672        internalSetPadding(left, top, right, bottom);
13673    }
13674
13675    private void internalSetPadding(int left, int top, int right, int bottom) {
13676        mUserPaddingLeft = left;
13677        mUserPaddingRight = right;
13678        mUserPaddingBottom = bottom;
13679
13680        final int viewFlags = mViewFlags;
13681        boolean changed = false;
13682
13683        // Common case is there are no scroll bars.
13684        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
13685            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
13686                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
13687                        ? 0 : getVerticalScrollbarWidth();
13688                switch (mVerticalScrollbarPosition) {
13689                    case SCROLLBAR_POSITION_DEFAULT:
13690                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13691                            left += offset;
13692                        } else {
13693                            right += offset;
13694                        }
13695                        break;
13696                    case SCROLLBAR_POSITION_RIGHT:
13697                        right += offset;
13698                        break;
13699                    case SCROLLBAR_POSITION_LEFT:
13700                        left += offset;
13701                        break;
13702                }
13703            }
13704            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
13705                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
13706                        ? 0 : getHorizontalScrollbarHeight();
13707            }
13708        }
13709
13710        if (mPaddingLeft != left) {
13711            changed = true;
13712            mPaddingLeft = left;
13713        }
13714        if (mPaddingTop != top) {
13715            changed = true;
13716            mPaddingTop = top;
13717        }
13718        if (mPaddingRight != right) {
13719            changed = true;
13720            mPaddingRight = right;
13721        }
13722        if (mPaddingBottom != bottom) {
13723            changed = true;
13724            mPaddingBottom = bottom;
13725        }
13726
13727        if (changed) {
13728            requestLayout();
13729        }
13730    }
13731
13732    /**
13733     * Sets the relative padding. The view may add on the space required to display
13734     * the scrollbars, depending on the style and visibility of the scrollbars.
13735     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
13736     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
13737     * from the values set in this call.
13738     *
13739     * @attr ref android.R.styleable#View_padding
13740     * @attr ref android.R.styleable#View_paddingBottom
13741     * @attr ref android.R.styleable#View_paddingStart
13742     * @attr ref android.R.styleable#View_paddingEnd
13743     * @attr ref android.R.styleable#View_paddingTop
13744     * @param start the start padding in pixels
13745     * @param top the top padding in pixels
13746     * @param end the end padding in pixels
13747     * @param bottom the bottom padding in pixels
13748     */
13749    public void setPaddingRelative(int start, int top, int end, int bottom) {
13750        mUserPaddingStart = start;
13751        mUserPaddingEnd = end;
13752        mUserPaddingRelative = true;
13753
13754        switch(getResolvedLayoutDirection()) {
13755            case LAYOUT_DIRECTION_RTL:
13756                internalSetPadding(end, top, start, bottom);
13757                break;
13758            case LAYOUT_DIRECTION_LTR:
13759            default:
13760                internalSetPadding(start, top, end, bottom);
13761        }
13762    }
13763
13764    /**
13765     * Returns the top padding of this view.
13766     *
13767     * @return the top padding in pixels
13768     */
13769    public int getPaddingTop() {
13770        return mPaddingTop;
13771    }
13772
13773    /**
13774     * Returns the bottom padding of this view. If there are inset and enabled
13775     * scrollbars, this value may include the space required to display the
13776     * scrollbars as well.
13777     *
13778     * @return the bottom padding in pixels
13779     */
13780    public int getPaddingBottom() {
13781        return mPaddingBottom;
13782    }
13783
13784    /**
13785     * Returns the left padding of this view. If there are inset and enabled
13786     * scrollbars, this value may include the space required to display the
13787     * scrollbars as well.
13788     *
13789     * @return the left padding in pixels
13790     */
13791    public int getPaddingLeft() {
13792        return mPaddingLeft;
13793    }
13794
13795    /**
13796     * Returns the start padding of this view depending on its resolved layout direction.
13797     * If there are inset and enabled scrollbars, this value may include the space
13798     * required to display the scrollbars as well.
13799     *
13800     * @return the start padding in pixels
13801     */
13802    public int getPaddingStart() {
13803        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13804                mPaddingRight : mPaddingLeft;
13805    }
13806
13807    /**
13808     * Returns the right padding of this view. If there are inset and enabled
13809     * scrollbars, this value may include the space required to display the
13810     * scrollbars as well.
13811     *
13812     * @return the right padding in pixels
13813     */
13814    public int getPaddingRight() {
13815        return mPaddingRight;
13816    }
13817
13818    /**
13819     * Returns the end padding of this view depending on its resolved layout direction.
13820     * If there are inset and enabled scrollbars, this value may include the space
13821     * required to display the scrollbars as well.
13822     *
13823     * @return the end padding in pixels
13824     */
13825    public int getPaddingEnd() {
13826        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13827                mPaddingLeft : mPaddingRight;
13828    }
13829
13830    /**
13831     * Return if the padding as been set thru relative values
13832     * {@link #setPaddingRelative(int, int, int, int)} or thru
13833     * @attr ref android.R.styleable#View_paddingStart or
13834     * @attr ref android.R.styleable#View_paddingEnd
13835     *
13836     * @return true if the padding is relative or false if it is not.
13837     */
13838    public boolean isPaddingRelative() {
13839        return mUserPaddingRelative;
13840    }
13841
13842    /**
13843     * @hide
13844     */
13845    public Insets getLayoutInsets() {
13846        if (mLayoutInsets == null) {
13847            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
13848        }
13849        return mLayoutInsets;
13850    }
13851
13852    /**
13853     * @hide
13854     */
13855    public void setLayoutInsets(Insets layoutInsets) {
13856        mLayoutInsets = layoutInsets;
13857    }
13858
13859    /**
13860     * Changes the selection state of this view. A view can be selected or not.
13861     * Note that selection is not the same as focus. Views are typically
13862     * selected in the context of an AdapterView like ListView or GridView;
13863     * the selected view is the view that is highlighted.
13864     *
13865     * @param selected true if the view must be selected, false otherwise
13866     */
13867    public void setSelected(boolean selected) {
13868        if (((mPrivateFlags & SELECTED) != 0) != selected) {
13869            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
13870            if (!selected) resetPressedState();
13871            invalidate(true);
13872            refreshDrawableState();
13873            dispatchSetSelected(selected);
13874            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13875                notifyAccessibilityStateChanged();
13876            }
13877        }
13878    }
13879
13880    /**
13881     * Dispatch setSelected to all of this View's children.
13882     *
13883     * @see #setSelected(boolean)
13884     *
13885     * @param selected The new selected state
13886     */
13887    protected void dispatchSetSelected(boolean selected) {
13888    }
13889
13890    /**
13891     * Indicates the selection state of this view.
13892     *
13893     * @return true if the view is selected, false otherwise
13894     */
13895    @ViewDebug.ExportedProperty
13896    public boolean isSelected() {
13897        return (mPrivateFlags & SELECTED) != 0;
13898    }
13899
13900    /**
13901     * Changes the activated state of this view. A view can be activated or not.
13902     * Note that activation is not the same as selection.  Selection is
13903     * a transient property, representing the view (hierarchy) the user is
13904     * currently interacting with.  Activation is a longer-term state that the
13905     * user can move views in and out of.  For example, in a list view with
13906     * single or multiple selection enabled, the views in the current selection
13907     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
13908     * here.)  The activated state is propagated down to children of the view it
13909     * is set on.
13910     *
13911     * @param activated true if the view must be activated, false otherwise
13912     */
13913    public void setActivated(boolean activated) {
13914        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
13915            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
13916            invalidate(true);
13917            refreshDrawableState();
13918            dispatchSetActivated(activated);
13919        }
13920    }
13921
13922    /**
13923     * Dispatch setActivated to all of this View's children.
13924     *
13925     * @see #setActivated(boolean)
13926     *
13927     * @param activated The new activated state
13928     */
13929    protected void dispatchSetActivated(boolean activated) {
13930    }
13931
13932    /**
13933     * Indicates the activation state of this view.
13934     *
13935     * @return true if the view is activated, false otherwise
13936     */
13937    @ViewDebug.ExportedProperty
13938    public boolean isActivated() {
13939        return (mPrivateFlags & ACTIVATED) != 0;
13940    }
13941
13942    /**
13943     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
13944     * observer can be used to get notifications when global events, like
13945     * layout, happen.
13946     *
13947     * The returned ViewTreeObserver observer is not guaranteed to remain
13948     * valid for the lifetime of this View. If the caller of this method keeps
13949     * a long-lived reference to ViewTreeObserver, it should always check for
13950     * the return value of {@link ViewTreeObserver#isAlive()}.
13951     *
13952     * @return The ViewTreeObserver for this view's hierarchy.
13953     */
13954    public ViewTreeObserver getViewTreeObserver() {
13955        if (mAttachInfo != null) {
13956            return mAttachInfo.mTreeObserver;
13957        }
13958        if (mFloatingTreeObserver == null) {
13959            mFloatingTreeObserver = new ViewTreeObserver();
13960        }
13961        return mFloatingTreeObserver;
13962    }
13963
13964    /**
13965     * <p>Finds the topmost view in the current view hierarchy.</p>
13966     *
13967     * @return the topmost view containing this view
13968     */
13969    public View getRootView() {
13970        if (mAttachInfo != null) {
13971            final View v = mAttachInfo.mRootView;
13972            if (v != null) {
13973                return v;
13974            }
13975        }
13976
13977        View parent = this;
13978
13979        while (parent.mParent != null && parent.mParent instanceof View) {
13980            parent = (View) parent.mParent;
13981        }
13982
13983        return parent;
13984    }
13985
13986    /**
13987     * <p>Computes the coordinates of this view on the screen. The argument
13988     * must be an array of two integers. After the method returns, the array
13989     * contains the x and y location in that order.</p>
13990     *
13991     * @param location an array of two integers in which to hold the coordinates
13992     */
13993    public void getLocationOnScreen(int[] location) {
13994        getLocationInWindow(location);
13995
13996        final AttachInfo info = mAttachInfo;
13997        if (info != null) {
13998            location[0] += info.mWindowLeft;
13999            location[1] += info.mWindowTop;
14000        }
14001    }
14002
14003    /**
14004     * <p>Computes the coordinates of this view in its window. The argument
14005     * must be an array of two integers. After the method returns, the array
14006     * contains the x and y location in that order.</p>
14007     *
14008     * @param location an array of two integers in which to hold the coordinates
14009     */
14010    public void getLocationInWindow(int[] location) {
14011        if (location == null || location.length < 2) {
14012            throw new IllegalArgumentException("location must be an array of two integers");
14013        }
14014
14015        if (mAttachInfo == null) {
14016            // When the view is not attached to a window, this method does not make sense
14017            location[0] = location[1] = 0;
14018            return;
14019        }
14020
14021        float[] position = mAttachInfo.mTmpTransformLocation;
14022        position[0] = position[1] = 0.0f;
14023
14024        if (!hasIdentityMatrix()) {
14025            getMatrix().mapPoints(position);
14026        }
14027
14028        position[0] += mLeft;
14029        position[1] += mTop;
14030
14031        ViewParent viewParent = mParent;
14032        while (viewParent instanceof View) {
14033            final View view = (View) viewParent;
14034
14035            position[0] -= view.mScrollX;
14036            position[1] -= view.mScrollY;
14037
14038            if (!view.hasIdentityMatrix()) {
14039                view.getMatrix().mapPoints(position);
14040            }
14041
14042            position[0] += view.mLeft;
14043            position[1] += view.mTop;
14044
14045            viewParent = view.mParent;
14046         }
14047
14048        if (viewParent instanceof ViewRootImpl) {
14049            // *cough*
14050            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14051            position[1] -= vr.mCurScrollY;
14052        }
14053
14054        location[0] = (int) (position[0] + 0.5f);
14055        location[1] = (int) (position[1] + 0.5f);
14056    }
14057
14058    /**
14059     * {@hide}
14060     * @param id the id of the view to be found
14061     * @return the view of the specified id, null if cannot be found
14062     */
14063    protected View findViewTraversal(int id) {
14064        if (id == mID) {
14065            return this;
14066        }
14067        return null;
14068    }
14069
14070    /**
14071     * {@hide}
14072     * @param tag the tag of the view to be found
14073     * @return the view of specified tag, null if cannot be found
14074     */
14075    protected View findViewWithTagTraversal(Object tag) {
14076        if (tag != null && tag.equals(mTag)) {
14077            return this;
14078        }
14079        return null;
14080    }
14081
14082    /**
14083     * {@hide}
14084     * @param predicate The predicate to evaluate.
14085     * @param childToSkip If not null, ignores this child during the recursive traversal.
14086     * @return The first view that matches the predicate or null.
14087     */
14088    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14089        if (predicate.apply(this)) {
14090            return this;
14091        }
14092        return null;
14093    }
14094
14095    /**
14096     * Look for a child view with the given id.  If this view has the given
14097     * id, return this view.
14098     *
14099     * @param id The id to search for.
14100     * @return The view that has the given id in the hierarchy or null
14101     */
14102    public final View findViewById(int id) {
14103        if (id < 0) {
14104            return null;
14105        }
14106        return findViewTraversal(id);
14107    }
14108
14109    /**
14110     * Finds a view by its unuque and stable accessibility id.
14111     *
14112     * @param accessibilityId The searched accessibility id.
14113     * @return The found view.
14114     */
14115    final View findViewByAccessibilityId(int accessibilityId) {
14116        if (accessibilityId < 0) {
14117            return null;
14118        }
14119        return findViewByAccessibilityIdTraversal(accessibilityId);
14120    }
14121
14122    /**
14123     * Performs the traversal to find a view by its unuque and stable accessibility id.
14124     *
14125     * <strong>Note:</strong>This method does not stop at the root namespace
14126     * boundary since the user can touch the screen at an arbitrary location
14127     * potentially crossing the root namespace bounday which will send an
14128     * accessibility event to accessibility services and they should be able
14129     * to obtain the event source. Also accessibility ids are guaranteed to be
14130     * unique in the window.
14131     *
14132     * @param accessibilityId The accessibility id.
14133     * @return The found view.
14134     */
14135    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14136        if (getAccessibilityViewId() == accessibilityId) {
14137            return this;
14138        }
14139        return null;
14140    }
14141
14142    /**
14143     * Look for a child view with the given tag.  If this view has the given
14144     * tag, return this view.
14145     *
14146     * @param tag The tag to search for, using "tag.equals(getTag())".
14147     * @return The View that has the given tag in the hierarchy or null
14148     */
14149    public final View findViewWithTag(Object tag) {
14150        if (tag == null) {
14151            return null;
14152        }
14153        return findViewWithTagTraversal(tag);
14154    }
14155
14156    /**
14157     * {@hide}
14158     * Look for a child view that matches the specified predicate.
14159     * If this view matches the predicate, return this view.
14160     *
14161     * @param predicate The predicate to evaluate.
14162     * @return The first view that matches the predicate or null.
14163     */
14164    public final View findViewByPredicate(Predicate<View> predicate) {
14165        return findViewByPredicateTraversal(predicate, null);
14166    }
14167
14168    /**
14169     * {@hide}
14170     * Look for a child view that matches the specified predicate,
14171     * starting with the specified view and its descendents and then
14172     * recusively searching the ancestors and siblings of that view
14173     * until this view is reached.
14174     *
14175     * This method is useful in cases where the predicate does not match
14176     * a single unique view (perhaps multiple views use the same id)
14177     * and we are trying to find the view that is "closest" in scope to the
14178     * starting view.
14179     *
14180     * @param start The view to start from.
14181     * @param predicate The predicate to evaluate.
14182     * @return The first view that matches the predicate or null.
14183     */
14184    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14185        View childToSkip = null;
14186        for (;;) {
14187            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14188            if (view != null || start == this) {
14189                return view;
14190            }
14191
14192            ViewParent parent = start.getParent();
14193            if (parent == null || !(parent instanceof View)) {
14194                return null;
14195            }
14196
14197            childToSkip = start;
14198            start = (View) parent;
14199        }
14200    }
14201
14202    /**
14203     * Sets the identifier for this view. The identifier does not have to be
14204     * unique in this view's hierarchy. The identifier should be a positive
14205     * number.
14206     *
14207     * @see #NO_ID
14208     * @see #getId()
14209     * @see #findViewById(int)
14210     *
14211     * @param id a number used to identify the view
14212     *
14213     * @attr ref android.R.styleable#View_id
14214     */
14215    public void setId(int id) {
14216        mID = id;
14217    }
14218
14219    /**
14220     * {@hide}
14221     *
14222     * @param isRoot true if the view belongs to the root namespace, false
14223     *        otherwise
14224     */
14225    public void setIsRootNamespace(boolean isRoot) {
14226        if (isRoot) {
14227            mPrivateFlags |= IS_ROOT_NAMESPACE;
14228        } else {
14229            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14230        }
14231    }
14232
14233    /**
14234     * {@hide}
14235     *
14236     * @return true if the view belongs to the root namespace, false otherwise
14237     */
14238    public boolean isRootNamespace() {
14239        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14240    }
14241
14242    /**
14243     * Returns this view's identifier.
14244     *
14245     * @return a positive integer used to identify the view or {@link #NO_ID}
14246     *         if the view has no ID
14247     *
14248     * @see #setId(int)
14249     * @see #findViewById(int)
14250     * @attr ref android.R.styleable#View_id
14251     */
14252    @ViewDebug.CapturedViewProperty
14253    public int getId() {
14254        return mID;
14255    }
14256
14257    /**
14258     * Returns this view's tag.
14259     *
14260     * @return the Object stored in this view as a tag
14261     *
14262     * @see #setTag(Object)
14263     * @see #getTag(int)
14264     */
14265    @ViewDebug.ExportedProperty
14266    public Object getTag() {
14267        return mTag;
14268    }
14269
14270    /**
14271     * Sets the tag associated with this view. A tag can be used to mark
14272     * a view in its hierarchy and does not have to be unique within the
14273     * hierarchy. Tags can also be used to store data within a view without
14274     * resorting to another data structure.
14275     *
14276     * @param tag an Object to tag the view with
14277     *
14278     * @see #getTag()
14279     * @see #setTag(int, Object)
14280     */
14281    public void setTag(final Object tag) {
14282        mTag = tag;
14283    }
14284
14285    /**
14286     * Returns the tag associated with this view and the specified key.
14287     *
14288     * @param key The key identifying the tag
14289     *
14290     * @return the Object stored in this view as a tag
14291     *
14292     * @see #setTag(int, Object)
14293     * @see #getTag()
14294     */
14295    public Object getTag(int key) {
14296        if (mKeyedTags != null) return mKeyedTags.get(key);
14297        return null;
14298    }
14299
14300    /**
14301     * Sets a tag associated with this view and a key. A tag can be used
14302     * to mark a view in its hierarchy and does not have to be unique within
14303     * the hierarchy. Tags can also be used to store data within a view
14304     * without resorting to another data structure.
14305     *
14306     * The specified key should be an id declared in the resources of the
14307     * application to ensure it is unique (see the <a
14308     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14309     * Keys identified as belonging to
14310     * the Android framework or not associated with any package will cause
14311     * an {@link IllegalArgumentException} to be thrown.
14312     *
14313     * @param key The key identifying the tag
14314     * @param tag An Object to tag the view with
14315     *
14316     * @throws IllegalArgumentException If they specified key is not valid
14317     *
14318     * @see #setTag(Object)
14319     * @see #getTag(int)
14320     */
14321    public void setTag(int key, final Object tag) {
14322        // If the package id is 0x00 or 0x01, it's either an undefined package
14323        // or a framework id
14324        if ((key >>> 24) < 2) {
14325            throw new IllegalArgumentException("The key must be an application-specific "
14326                    + "resource id.");
14327        }
14328
14329        setKeyedTag(key, tag);
14330    }
14331
14332    /**
14333     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14334     * framework id.
14335     *
14336     * @hide
14337     */
14338    public void setTagInternal(int key, Object tag) {
14339        if ((key >>> 24) != 0x1) {
14340            throw new IllegalArgumentException("The key must be a framework-specific "
14341                    + "resource id.");
14342        }
14343
14344        setKeyedTag(key, tag);
14345    }
14346
14347    private void setKeyedTag(int key, Object tag) {
14348        if (mKeyedTags == null) {
14349            mKeyedTags = new SparseArray<Object>();
14350        }
14351
14352        mKeyedTags.put(key, tag);
14353    }
14354
14355    /**
14356     * @param consistency The type of consistency. See ViewDebug for more information.
14357     *
14358     * @hide
14359     */
14360    protected boolean dispatchConsistencyCheck(int consistency) {
14361        return onConsistencyCheck(consistency);
14362    }
14363
14364    /**
14365     * Method that subclasses should implement to check their consistency. The type of
14366     * consistency check is indicated by the bit field passed as a parameter.
14367     *
14368     * @param consistency The type of consistency. See ViewDebug for more information.
14369     *
14370     * @throws IllegalStateException if the view is in an inconsistent state.
14371     *
14372     * @hide
14373     */
14374    protected boolean onConsistencyCheck(int consistency) {
14375        boolean result = true;
14376
14377        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14378        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14379
14380        if (checkLayout) {
14381            if (getParent() == null) {
14382                result = false;
14383                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14384                        "View " + this + " does not have a parent.");
14385            }
14386
14387            if (mAttachInfo == null) {
14388                result = false;
14389                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14390                        "View " + this + " is not attached to a window.");
14391            }
14392        }
14393
14394        if (checkDrawing) {
14395            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14396            // from their draw() method
14397
14398            if ((mPrivateFlags & DRAWN) != DRAWN &&
14399                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14400                result = false;
14401                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14402                        "View " + this + " was invalidated but its drawing cache is valid.");
14403            }
14404        }
14405
14406        return result;
14407    }
14408
14409    /**
14410     * Prints information about this view in the log output, with the tag
14411     * {@link #VIEW_LOG_TAG}.
14412     *
14413     * @hide
14414     */
14415    public void debug() {
14416        debug(0);
14417    }
14418
14419    /**
14420     * Prints information about this view in the log output, with the tag
14421     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14422     * indentation defined by the <code>depth</code>.
14423     *
14424     * @param depth the indentation level
14425     *
14426     * @hide
14427     */
14428    protected void debug(int depth) {
14429        String output = debugIndent(depth - 1);
14430
14431        output += "+ " + this;
14432        int id = getId();
14433        if (id != -1) {
14434            output += " (id=" + id + ")";
14435        }
14436        Object tag = getTag();
14437        if (tag != null) {
14438            output += " (tag=" + tag + ")";
14439        }
14440        Log.d(VIEW_LOG_TAG, output);
14441
14442        if ((mPrivateFlags & FOCUSED) != 0) {
14443            output = debugIndent(depth) + " FOCUSED";
14444            Log.d(VIEW_LOG_TAG, output);
14445        }
14446
14447        output = debugIndent(depth);
14448        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14449                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14450                + "} ";
14451        Log.d(VIEW_LOG_TAG, output);
14452
14453        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14454                || mPaddingBottom != 0) {
14455            output = debugIndent(depth);
14456            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14457                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14458            Log.d(VIEW_LOG_TAG, output);
14459        }
14460
14461        output = debugIndent(depth);
14462        output += "mMeasureWidth=" + mMeasuredWidth +
14463                " mMeasureHeight=" + mMeasuredHeight;
14464        Log.d(VIEW_LOG_TAG, output);
14465
14466        output = debugIndent(depth);
14467        if (mLayoutParams == null) {
14468            output += "BAD! no layout params";
14469        } else {
14470            output = mLayoutParams.debug(output);
14471        }
14472        Log.d(VIEW_LOG_TAG, output);
14473
14474        output = debugIndent(depth);
14475        output += "flags={";
14476        output += View.printFlags(mViewFlags);
14477        output += "}";
14478        Log.d(VIEW_LOG_TAG, output);
14479
14480        output = debugIndent(depth);
14481        output += "privateFlags={";
14482        output += View.printPrivateFlags(mPrivateFlags);
14483        output += "}";
14484        Log.d(VIEW_LOG_TAG, output);
14485    }
14486
14487    /**
14488     * Creates a string of whitespaces used for indentation.
14489     *
14490     * @param depth the indentation level
14491     * @return a String containing (depth * 2 + 3) * 2 white spaces
14492     *
14493     * @hide
14494     */
14495    protected static String debugIndent(int depth) {
14496        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14497        for (int i = 0; i < (depth * 2) + 3; i++) {
14498            spaces.append(' ').append(' ');
14499        }
14500        return spaces.toString();
14501    }
14502
14503    /**
14504     * <p>Return the offset of the widget's text baseline from the widget's top
14505     * boundary. If this widget does not support baseline alignment, this
14506     * method returns -1. </p>
14507     *
14508     * @return the offset of the baseline within the widget's bounds or -1
14509     *         if baseline alignment is not supported
14510     */
14511    @ViewDebug.ExportedProperty(category = "layout")
14512    public int getBaseline() {
14513        return -1;
14514    }
14515
14516    /**
14517     * Call this when something has changed which has invalidated the
14518     * layout of this view. This will schedule a layout pass of the view
14519     * tree.
14520     */
14521    public void requestLayout() {
14522        if (ViewDebug.TRACE_HIERARCHY) {
14523            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14524        }
14525
14526        mPrivateFlags |= FORCE_LAYOUT;
14527        mPrivateFlags |= INVALIDATED;
14528
14529        if (mLayoutParams != null) {
14530            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14531        }
14532
14533        if (mParent != null && !mParent.isLayoutRequested()) {
14534            mParent.requestLayout();
14535        }
14536    }
14537
14538    /**
14539     * Forces this view to be laid out during the next layout pass.
14540     * This method does not call requestLayout() or forceLayout()
14541     * on the parent.
14542     */
14543    public void forceLayout() {
14544        mPrivateFlags |= FORCE_LAYOUT;
14545        mPrivateFlags |= INVALIDATED;
14546    }
14547
14548    /**
14549     * <p>
14550     * This is called to find out how big a view should be. The parent
14551     * supplies constraint information in the width and height parameters.
14552     * </p>
14553     *
14554     * <p>
14555     * The actual measurement work of a view is performed in
14556     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14557     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14558     * </p>
14559     *
14560     *
14561     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14562     *        parent
14563     * @param heightMeasureSpec Vertical space requirements as imposed by the
14564     *        parent
14565     *
14566     * @see #onMeasure(int, int)
14567     */
14568    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14569        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14570                widthMeasureSpec != mOldWidthMeasureSpec ||
14571                heightMeasureSpec != mOldHeightMeasureSpec) {
14572
14573            // first clears the measured dimension flag
14574            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14575
14576            if (ViewDebug.TRACE_HIERARCHY) {
14577                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14578            }
14579
14580            // measure ourselves, this should set the measured dimension flag back
14581            onMeasure(widthMeasureSpec, heightMeasureSpec);
14582
14583            // flag not set, setMeasuredDimension() was not invoked, we raise
14584            // an exception to warn the developer
14585            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14586                throw new IllegalStateException("onMeasure() did not set the"
14587                        + " measured dimension by calling"
14588                        + " setMeasuredDimension()");
14589            }
14590
14591            mPrivateFlags |= LAYOUT_REQUIRED;
14592        }
14593
14594        mOldWidthMeasureSpec = widthMeasureSpec;
14595        mOldHeightMeasureSpec = heightMeasureSpec;
14596    }
14597
14598    /**
14599     * <p>
14600     * Measure the view and its content to determine the measured width and the
14601     * measured height. This method is invoked by {@link #measure(int, int)} and
14602     * should be overriden by subclasses to provide accurate and efficient
14603     * measurement of their contents.
14604     * </p>
14605     *
14606     * <p>
14607     * <strong>CONTRACT:</strong> When overriding this method, you
14608     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14609     * measured width and height of this view. Failure to do so will trigger an
14610     * <code>IllegalStateException</code>, thrown by
14611     * {@link #measure(int, int)}. Calling the superclass'
14612     * {@link #onMeasure(int, int)} is a valid use.
14613     * </p>
14614     *
14615     * <p>
14616     * The base class implementation of measure defaults to the background size,
14617     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14618     * override {@link #onMeasure(int, int)} to provide better measurements of
14619     * their content.
14620     * </p>
14621     *
14622     * <p>
14623     * If this method is overridden, it is the subclass's responsibility to make
14624     * sure the measured height and width are at least the view's minimum height
14625     * and width ({@link #getSuggestedMinimumHeight()} and
14626     * {@link #getSuggestedMinimumWidth()}).
14627     * </p>
14628     *
14629     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14630     *                         The requirements are encoded with
14631     *                         {@link android.view.View.MeasureSpec}.
14632     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14633     *                         The requirements are encoded with
14634     *                         {@link android.view.View.MeasureSpec}.
14635     *
14636     * @see #getMeasuredWidth()
14637     * @see #getMeasuredHeight()
14638     * @see #setMeasuredDimension(int, int)
14639     * @see #getSuggestedMinimumHeight()
14640     * @see #getSuggestedMinimumWidth()
14641     * @see android.view.View.MeasureSpec#getMode(int)
14642     * @see android.view.View.MeasureSpec#getSize(int)
14643     */
14644    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14645        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14646                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14647    }
14648
14649    /**
14650     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14651     * measured width and measured height. Failing to do so will trigger an
14652     * exception at measurement time.</p>
14653     *
14654     * @param measuredWidth The measured width of this view.  May be a complex
14655     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14656     * {@link #MEASURED_STATE_TOO_SMALL}.
14657     * @param measuredHeight The measured height of this view.  May be a complex
14658     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14659     * {@link #MEASURED_STATE_TOO_SMALL}.
14660     */
14661    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14662        mMeasuredWidth = measuredWidth;
14663        mMeasuredHeight = measuredHeight;
14664
14665        mPrivateFlags |= MEASURED_DIMENSION_SET;
14666    }
14667
14668    /**
14669     * Merge two states as returned by {@link #getMeasuredState()}.
14670     * @param curState The current state as returned from a view or the result
14671     * of combining multiple views.
14672     * @param newState The new view state to combine.
14673     * @return Returns a new integer reflecting the combination of the two
14674     * states.
14675     */
14676    public static int combineMeasuredStates(int curState, int newState) {
14677        return curState | newState;
14678    }
14679
14680    /**
14681     * Version of {@link #resolveSizeAndState(int, int, int)}
14682     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14683     */
14684    public static int resolveSize(int size, int measureSpec) {
14685        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14686    }
14687
14688    /**
14689     * Utility to reconcile a desired size and state, with constraints imposed
14690     * by a MeasureSpec.  Will take the desired size, unless a different size
14691     * is imposed by the constraints.  The returned value is a compound integer,
14692     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
14693     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
14694     * size is smaller than the size the view wants to be.
14695     *
14696     * @param size How big the view wants to be
14697     * @param measureSpec Constraints imposed by the parent
14698     * @return Size information bit mask as defined by
14699     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14700     */
14701    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
14702        int result = size;
14703        int specMode = MeasureSpec.getMode(measureSpec);
14704        int specSize =  MeasureSpec.getSize(measureSpec);
14705        switch (specMode) {
14706        case MeasureSpec.UNSPECIFIED:
14707            result = size;
14708            break;
14709        case MeasureSpec.AT_MOST:
14710            if (specSize < size) {
14711                result = specSize | MEASURED_STATE_TOO_SMALL;
14712            } else {
14713                result = size;
14714            }
14715            break;
14716        case MeasureSpec.EXACTLY:
14717            result = specSize;
14718            break;
14719        }
14720        return result | (childMeasuredState&MEASURED_STATE_MASK);
14721    }
14722
14723    /**
14724     * Utility to return a default size. Uses the supplied size if the
14725     * MeasureSpec imposed no constraints. Will get larger if allowed
14726     * by the MeasureSpec.
14727     *
14728     * @param size Default size for this view
14729     * @param measureSpec Constraints imposed by the parent
14730     * @return The size this view should be.
14731     */
14732    public static int getDefaultSize(int size, int measureSpec) {
14733        int result = size;
14734        int specMode = MeasureSpec.getMode(measureSpec);
14735        int specSize = MeasureSpec.getSize(measureSpec);
14736
14737        switch (specMode) {
14738        case MeasureSpec.UNSPECIFIED:
14739            result = size;
14740            break;
14741        case MeasureSpec.AT_MOST:
14742        case MeasureSpec.EXACTLY:
14743            result = specSize;
14744            break;
14745        }
14746        return result;
14747    }
14748
14749    /**
14750     * Returns the suggested minimum height that the view should use. This
14751     * returns the maximum of the view's minimum height
14752     * and the background's minimum height
14753     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
14754     * <p>
14755     * When being used in {@link #onMeasure(int, int)}, the caller should still
14756     * ensure the returned height is within the requirements of the parent.
14757     *
14758     * @return The suggested minimum height of the view.
14759     */
14760    protected int getSuggestedMinimumHeight() {
14761        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
14762
14763    }
14764
14765    /**
14766     * Returns the suggested minimum width that the view should use. This
14767     * returns the maximum of the view's minimum width)
14768     * and the background's minimum width
14769     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
14770     * <p>
14771     * When being used in {@link #onMeasure(int, int)}, the caller should still
14772     * ensure the returned width is within the requirements of the parent.
14773     *
14774     * @return The suggested minimum width of the view.
14775     */
14776    protected int getSuggestedMinimumWidth() {
14777        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
14778    }
14779
14780    /**
14781     * Returns the minimum height of the view.
14782     *
14783     * @return the minimum height the view will try to be.
14784     *
14785     * @see #setMinimumHeight(int)
14786     *
14787     * @attr ref android.R.styleable#View_minHeight
14788     */
14789    public int getMinimumHeight() {
14790        return mMinHeight;
14791    }
14792
14793    /**
14794     * Sets the minimum height of the view. It is not guaranteed the view will
14795     * be able to achieve this minimum height (for example, if its parent layout
14796     * constrains it with less available height).
14797     *
14798     * @param minHeight The minimum height the view will try to be.
14799     *
14800     * @see #getMinimumHeight()
14801     *
14802     * @attr ref android.R.styleable#View_minHeight
14803     */
14804    public void setMinimumHeight(int minHeight) {
14805        mMinHeight = minHeight;
14806        requestLayout();
14807    }
14808
14809    /**
14810     * Returns the minimum width of the view.
14811     *
14812     * @return the minimum width the view will try to be.
14813     *
14814     * @see #setMinimumWidth(int)
14815     *
14816     * @attr ref android.R.styleable#View_minWidth
14817     */
14818    public int getMinimumWidth() {
14819        return mMinWidth;
14820    }
14821
14822    /**
14823     * Sets the minimum width of the view. It is not guaranteed the view will
14824     * be able to achieve this minimum width (for example, if its parent layout
14825     * constrains it with less available width).
14826     *
14827     * @param minWidth The minimum width the view will try to be.
14828     *
14829     * @see #getMinimumWidth()
14830     *
14831     * @attr ref android.R.styleable#View_minWidth
14832     */
14833    public void setMinimumWidth(int minWidth) {
14834        mMinWidth = minWidth;
14835        requestLayout();
14836
14837    }
14838
14839    /**
14840     * Get the animation currently associated with this view.
14841     *
14842     * @return The animation that is currently playing or
14843     *         scheduled to play for this view.
14844     */
14845    public Animation getAnimation() {
14846        return mCurrentAnimation;
14847    }
14848
14849    /**
14850     * Start the specified animation now.
14851     *
14852     * @param animation the animation to start now
14853     */
14854    public void startAnimation(Animation animation) {
14855        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
14856        setAnimation(animation);
14857        invalidateParentCaches();
14858        invalidate(true);
14859    }
14860
14861    /**
14862     * Cancels any animations for this view.
14863     */
14864    public void clearAnimation() {
14865        if (mCurrentAnimation != null) {
14866            mCurrentAnimation.detach();
14867        }
14868        mCurrentAnimation = null;
14869        invalidateParentIfNeeded();
14870    }
14871
14872    /**
14873     * Sets the next animation to play for this view.
14874     * If you want the animation to play immediately, use
14875     * startAnimation. This method provides allows fine-grained
14876     * control over the start time and invalidation, but you
14877     * must make sure that 1) the animation has a start time set, and
14878     * 2) the view will be invalidated when the animation is supposed to
14879     * start.
14880     *
14881     * @param animation The next animation, or null.
14882     */
14883    public void setAnimation(Animation animation) {
14884        mCurrentAnimation = animation;
14885
14886        if (animation != null) {
14887            // If the screen is off assume the animation start time is now instead of
14888            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
14889            // would cause the animation to start when the screen turns back on
14890            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
14891                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
14892                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
14893            }
14894            animation.reset();
14895        }
14896    }
14897
14898    /**
14899     * Invoked by a parent ViewGroup to notify the start of the animation
14900     * currently associated with this view. If you override this method,
14901     * always call super.onAnimationStart();
14902     *
14903     * @see #setAnimation(android.view.animation.Animation)
14904     * @see #getAnimation()
14905     */
14906    protected void onAnimationStart() {
14907        mPrivateFlags |= ANIMATION_STARTED;
14908    }
14909
14910    /**
14911     * Invoked by a parent ViewGroup to notify the end of the animation
14912     * currently associated with this view. If you override this method,
14913     * always call super.onAnimationEnd();
14914     *
14915     * @see #setAnimation(android.view.animation.Animation)
14916     * @see #getAnimation()
14917     */
14918    protected void onAnimationEnd() {
14919        mPrivateFlags &= ~ANIMATION_STARTED;
14920    }
14921
14922    /**
14923     * Invoked if there is a Transform that involves alpha. Subclass that can
14924     * draw themselves with the specified alpha should return true, and then
14925     * respect that alpha when their onDraw() is called. If this returns false
14926     * then the view may be redirected to draw into an offscreen buffer to
14927     * fulfill the request, which will look fine, but may be slower than if the
14928     * subclass handles it internally. The default implementation returns false.
14929     *
14930     * @param alpha The alpha (0..255) to apply to the view's drawing
14931     * @return true if the view can draw with the specified alpha.
14932     */
14933    protected boolean onSetAlpha(int alpha) {
14934        return false;
14935    }
14936
14937    /**
14938     * This is used by the RootView to perform an optimization when
14939     * the view hierarchy contains one or several SurfaceView.
14940     * SurfaceView is always considered transparent, but its children are not,
14941     * therefore all View objects remove themselves from the global transparent
14942     * region (passed as a parameter to this function).
14943     *
14944     * @param region The transparent region for this ViewAncestor (window).
14945     *
14946     * @return Returns true if the effective visibility of the view at this
14947     * point is opaque, regardless of the transparent region; returns false
14948     * if it is possible for underlying windows to be seen behind the view.
14949     *
14950     * {@hide}
14951     */
14952    public boolean gatherTransparentRegion(Region region) {
14953        final AttachInfo attachInfo = mAttachInfo;
14954        if (region != null && attachInfo != null) {
14955            final int pflags = mPrivateFlags;
14956            if ((pflags & SKIP_DRAW) == 0) {
14957                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
14958                // remove it from the transparent region.
14959                final int[] location = attachInfo.mTransparentLocation;
14960                getLocationInWindow(location);
14961                region.op(location[0], location[1], location[0] + mRight - mLeft,
14962                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
14963            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
14964                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
14965                // exists, so we remove the background drawable's non-transparent
14966                // parts from this transparent region.
14967                applyDrawableToTransparentRegion(mBackground, region);
14968            }
14969        }
14970        return true;
14971    }
14972
14973    /**
14974     * Play a sound effect for this view.
14975     *
14976     * <p>The framework will play sound effects for some built in actions, such as
14977     * clicking, but you may wish to play these effects in your widget,
14978     * for instance, for internal navigation.
14979     *
14980     * <p>The sound effect will only be played if sound effects are enabled by the user, and
14981     * {@link #isSoundEffectsEnabled()} is true.
14982     *
14983     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
14984     */
14985    public void playSoundEffect(int soundConstant) {
14986        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
14987            return;
14988        }
14989        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
14990    }
14991
14992    /**
14993     * BZZZTT!!1!
14994     *
14995     * <p>Provide haptic feedback to the user for this view.
14996     *
14997     * <p>The framework will provide haptic feedback for some built in actions,
14998     * such as long presses, but you may wish to provide feedback for your
14999     * own widget.
15000     *
15001     * <p>The feedback will only be performed if
15002     * {@link #isHapticFeedbackEnabled()} is true.
15003     *
15004     * @param feedbackConstant One of the constants defined in
15005     * {@link HapticFeedbackConstants}
15006     */
15007    public boolean performHapticFeedback(int feedbackConstant) {
15008        return performHapticFeedback(feedbackConstant, 0);
15009    }
15010
15011    /**
15012     * BZZZTT!!1!
15013     *
15014     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15015     *
15016     * @param feedbackConstant One of the constants defined in
15017     * {@link HapticFeedbackConstants}
15018     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15019     */
15020    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15021        if (mAttachInfo == null) {
15022            return false;
15023        }
15024        //noinspection SimplifiableIfStatement
15025        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15026                && !isHapticFeedbackEnabled()) {
15027            return false;
15028        }
15029        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15030                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15031    }
15032
15033    /**
15034     * Request that the visibility of the status bar or other screen/window
15035     * decorations be changed.
15036     *
15037     * <p>This method is used to put the over device UI into temporary modes
15038     * where the user's attention is focused more on the application content,
15039     * by dimming or hiding surrounding system affordances.  This is typically
15040     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15041     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15042     * to be placed behind the action bar (and with these flags other system
15043     * affordances) so that smooth transitions between hiding and showing them
15044     * can be done.
15045     *
15046     * <p>Two representative examples of the use of system UI visibility is
15047     * implementing a content browsing application (like a magazine reader)
15048     * and a video playing application.
15049     *
15050     * <p>The first code shows a typical implementation of a View in a content
15051     * browsing application.  In this implementation, the application goes
15052     * into a content-oriented mode by hiding the status bar and action bar,
15053     * and putting the navigation elements into lights out mode.  The user can
15054     * then interact with content while in this mode.  Such an application should
15055     * provide an easy way for the user to toggle out of the mode (such as to
15056     * check information in the status bar or access notifications).  In the
15057     * implementation here, this is done simply by tapping on the content.
15058     *
15059     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15060     *      content}
15061     *
15062     * <p>This second code sample shows a typical implementation of a View
15063     * in a video playing application.  In this situation, while the video is
15064     * playing the application would like to go into a complete full-screen mode,
15065     * to use as much of the display as possible for the video.  When in this state
15066     * the user can not interact with the application; the system intercepts
15067     * touching on the screen to pop the UI out of full screen mode.
15068     *
15069     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15070     *      content}
15071     *
15072     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15073     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15074     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15075     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15076     */
15077    public void setSystemUiVisibility(int visibility) {
15078        if (visibility != mSystemUiVisibility) {
15079            mSystemUiVisibility = visibility;
15080            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15081                mParent.recomputeViewAttributes(this);
15082            }
15083        }
15084    }
15085
15086    /**
15087     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15088     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15089     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15090     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15091     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15092     */
15093    public int getSystemUiVisibility() {
15094        return mSystemUiVisibility;
15095    }
15096
15097    /**
15098     * Returns the current system UI visibility that is currently set for
15099     * the entire window.  This is the combination of the
15100     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15101     * views in the window.
15102     */
15103    public int getWindowSystemUiVisibility() {
15104        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15105    }
15106
15107    /**
15108     * Override to find out when the window's requested system UI visibility
15109     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15110     * This is different from the callbacks recieved through
15111     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15112     * in that this is only telling you about the local request of the window,
15113     * not the actual values applied by the system.
15114     */
15115    public void onWindowSystemUiVisibilityChanged(int visible) {
15116    }
15117
15118    /**
15119     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15120     * the view hierarchy.
15121     */
15122    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15123        onWindowSystemUiVisibilityChanged(visible);
15124    }
15125
15126    /**
15127     * Set a listener to receive callbacks when the visibility of the system bar changes.
15128     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15129     */
15130    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15131        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15132        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15133            mParent.recomputeViewAttributes(this);
15134        }
15135    }
15136
15137    /**
15138     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15139     * the view hierarchy.
15140     */
15141    public void dispatchSystemUiVisibilityChanged(int visibility) {
15142        ListenerInfo li = mListenerInfo;
15143        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15144            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15145                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15146        }
15147    }
15148
15149    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
15150        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15151        if (val != mSystemUiVisibility) {
15152            setSystemUiVisibility(val);
15153        }
15154    }
15155
15156    /**
15157     * Creates an image that the system displays during the drag and drop
15158     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15159     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15160     * appearance as the given View. The default also positions the center of the drag shadow
15161     * directly under the touch point. If no View is provided (the constructor with no parameters
15162     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15163     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15164     * default is an invisible drag shadow.
15165     * <p>
15166     * You are not required to use the View you provide to the constructor as the basis of the
15167     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15168     * anything you want as the drag shadow.
15169     * </p>
15170     * <p>
15171     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15172     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15173     *  size and position of the drag shadow. It uses this data to construct a
15174     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15175     *  so that your application can draw the shadow image in the Canvas.
15176     * </p>
15177     *
15178     * <div class="special reference">
15179     * <h3>Developer Guides</h3>
15180     * <p>For a guide to implementing drag and drop features, read the
15181     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15182     * </div>
15183     */
15184    public static class DragShadowBuilder {
15185        private final WeakReference<View> mView;
15186
15187        /**
15188         * Constructs a shadow image builder based on a View. By default, the resulting drag
15189         * shadow will have the same appearance and dimensions as the View, with the touch point
15190         * over the center of the View.
15191         * @param view A View. Any View in scope can be used.
15192         */
15193        public DragShadowBuilder(View view) {
15194            mView = new WeakReference<View>(view);
15195        }
15196
15197        /**
15198         * Construct a shadow builder object with no associated View.  This
15199         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15200         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15201         * to supply the drag shadow's dimensions and appearance without
15202         * reference to any View object. If they are not overridden, then the result is an
15203         * invisible drag shadow.
15204         */
15205        public DragShadowBuilder() {
15206            mView = new WeakReference<View>(null);
15207        }
15208
15209        /**
15210         * Returns the View object that had been passed to the
15211         * {@link #View.DragShadowBuilder(View)}
15212         * constructor.  If that View parameter was {@code null} or if the
15213         * {@link #View.DragShadowBuilder()}
15214         * constructor was used to instantiate the builder object, this method will return
15215         * null.
15216         *
15217         * @return The View object associate with this builder object.
15218         */
15219        @SuppressWarnings({"JavadocReference"})
15220        final public View getView() {
15221            return mView.get();
15222        }
15223
15224        /**
15225         * Provides the metrics for the shadow image. These include the dimensions of
15226         * the shadow image, and the point within that shadow that should
15227         * be centered under the touch location while dragging.
15228         * <p>
15229         * The default implementation sets the dimensions of the shadow to be the
15230         * same as the dimensions of the View itself and centers the shadow under
15231         * the touch point.
15232         * </p>
15233         *
15234         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15235         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15236         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15237         * image.
15238         *
15239         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15240         * shadow image that should be underneath the touch point during the drag and drop
15241         * operation. Your application must set {@link android.graphics.Point#x} to the
15242         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15243         */
15244        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15245            final View view = mView.get();
15246            if (view != null) {
15247                shadowSize.set(view.getWidth(), view.getHeight());
15248                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15249            } else {
15250                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15251            }
15252        }
15253
15254        /**
15255         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15256         * based on the dimensions it received from the
15257         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15258         *
15259         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15260         */
15261        public void onDrawShadow(Canvas canvas) {
15262            final View view = mView.get();
15263            if (view != null) {
15264                view.draw(canvas);
15265            } else {
15266                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15267            }
15268        }
15269    }
15270
15271    /**
15272     * Starts a drag and drop operation. When your application calls this method, it passes a
15273     * {@link android.view.View.DragShadowBuilder} object to the system. The
15274     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15275     * to get metrics for the drag shadow, and then calls the object's
15276     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15277     * <p>
15278     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15279     *  drag events to all the View objects in your application that are currently visible. It does
15280     *  this either by calling the View object's drag listener (an implementation of
15281     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15282     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15283     *  Both are passed a {@link android.view.DragEvent} object that has a
15284     *  {@link android.view.DragEvent#getAction()} value of
15285     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15286     * </p>
15287     * <p>
15288     * Your application can invoke startDrag() on any attached View object. The View object does not
15289     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15290     * be related to the View the user selected for dragging.
15291     * </p>
15292     * @param data A {@link android.content.ClipData} object pointing to the data to be
15293     * transferred by the drag and drop operation.
15294     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15295     * drag shadow.
15296     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15297     * drop operation. This Object is put into every DragEvent object sent by the system during the
15298     * current drag.
15299     * <p>
15300     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15301     * to the target Views. For example, it can contain flags that differentiate between a
15302     * a copy operation and a move operation.
15303     * </p>
15304     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15305     * so the parameter should be set to 0.
15306     * @return {@code true} if the method completes successfully, or
15307     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15308     * do a drag, and so no drag operation is in progress.
15309     */
15310    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15311            Object myLocalState, int flags) {
15312        if (ViewDebug.DEBUG_DRAG) {
15313            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15314        }
15315        boolean okay = false;
15316
15317        Point shadowSize = new Point();
15318        Point shadowTouchPoint = new Point();
15319        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15320
15321        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15322                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15323            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15324        }
15325
15326        if (ViewDebug.DEBUG_DRAG) {
15327            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15328                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15329        }
15330        Surface surface = new Surface();
15331        try {
15332            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15333                    flags, shadowSize.x, shadowSize.y, surface);
15334            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15335                    + " surface=" + surface);
15336            if (token != null) {
15337                Canvas canvas = surface.lockCanvas(null);
15338                try {
15339                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15340                    shadowBuilder.onDrawShadow(canvas);
15341                } finally {
15342                    surface.unlockCanvasAndPost(canvas);
15343                }
15344
15345                final ViewRootImpl root = getViewRootImpl();
15346
15347                // Cache the local state object for delivery with DragEvents
15348                root.setLocalDragState(myLocalState);
15349
15350                // repurpose 'shadowSize' for the last touch point
15351                root.getLastTouchPoint(shadowSize);
15352
15353                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15354                        shadowSize.x, shadowSize.y,
15355                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15356                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15357
15358                // Off and running!  Release our local surface instance; the drag
15359                // shadow surface is now managed by the system process.
15360                surface.release();
15361            }
15362        } catch (Exception e) {
15363            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15364            surface.destroy();
15365        }
15366
15367        return okay;
15368    }
15369
15370    /**
15371     * Handles drag events sent by the system following a call to
15372     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15373     *<p>
15374     * When the system calls this method, it passes a
15375     * {@link android.view.DragEvent} object. A call to
15376     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15377     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15378     * operation.
15379     * @param event The {@link android.view.DragEvent} sent by the system.
15380     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15381     * in DragEvent, indicating the type of drag event represented by this object.
15382     * @return {@code true} if the method was successful, otherwise {@code false}.
15383     * <p>
15384     *  The method should return {@code true} in response to an action type of
15385     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15386     *  operation.
15387     * </p>
15388     * <p>
15389     *  The method should also return {@code true} in response to an action type of
15390     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15391     *  {@code false} if it didn't.
15392     * </p>
15393     */
15394    public boolean onDragEvent(DragEvent event) {
15395        return false;
15396    }
15397
15398    /**
15399     * Detects if this View is enabled and has a drag event listener.
15400     * If both are true, then it calls the drag event listener with the
15401     * {@link android.view.DragEvent} it received. If the drag event listener returns
15402     * {@code true}, then dispatchDragEvent() returns {@code true}.
15403     * <p>
15404     * For all other cases, the method calls the
15405     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15406     * method and returns its result.
15407     * </p>
15408     * <p>
15409     * This ensures that a drag event is always consumed, even if the View does not have a drag
15410     * event listener. However, if the View has a listener and the listener returns true, then
15411     * onDragEvent() is not called.
15412     * </p>
15413     */
15414    public boolean dispatchDragEvent(DragEvent event) {
15415        //noinspection SimplifiableIfStatement
15416        ListenerInfo li = mListenerInfo;
15417        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15418                && li.mOnDragListener.onDrag(this, event)) {
15419            return true;
15420        }
15421        return onDragEvent(event);
15422    }
15423
15424    boolean canAcceptDrag() {
15425        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15426    }
15427
15428    /**
15429     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15430     * it is ever exposed at all.
15431     * @hide
15432     */
15433    public void onCloseSystemDialogs(String reason) {
15434    }
15435
15436    /**
15437     * Given a Drawable whose bounds have been set to draw into this view,
15438     * update a Region being computed for
15439     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15440     * that any non-transparent parts of the Drawable are removed from the
15441     * given transparent region.
15442     *
15443     * @param dr The Drawable whose transparency is to be applied to the region.
15444     * @param region A Region holding the current transparency information,
15445     * where any parts of the region that are set are considered to be
15446     * transparent.  On return, this region will be modified to have the
15447     * transparency information reduced by the corresponding parts of the
15448     * Drawable that are not transparent.
15449     * {@hide}
15450     */
15451    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15452        if (DBG) {
15453            Log.i("View", "Getting transparent region for: " + this);
15454        }
15455        final Region r = dr.getTransparentRegion();
15456        final Rect db = dr.getBounds();
15457        final AttachInfo attachInfo = mAttachInfo;
15458        if (r != null && attachInfo != null) {
15459            final int w = getRight()-getLeft();
15460            final int h = getBottom()-getTop();
15461            if (db.left > 0) {
15462                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15463                r.op(0, 0, db.left, h, Region.Op.UNION);
15464            }
15465            if (db.right < w) {
15466                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15467                r.op(db.right, 0, w, h, Region.Op.UNION);
15468            }
15469            if (db.top > 0) {
15470                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15471                r.op(0, 0, w, db.top, Region.Op.UNION);
15472            }
15473            if (db.bottom < h) {
15474                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15475                r.op(0, db.bottom, w, h, Region.Op.UNION);
15476            }
15477            final int[] location = attachInfo.mTransparentLocation;
15478            getLocationInWindow(location);
15479            r.translate(location[0], location[1]);
15480            region.op(r, Region.Op.INTERSECT);
15481        } else {
15482            region.op(db, Region.Op.DIFFERENCE);
15483        }
15484    }
15485
15486    private void checkForLongClick(int delayOffset) {
15487        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15488            mHasPerformedLongPress = false;
15489
15490            if (mPendingCheckForLongPress == null) {
15491                mPendingCheckForLongPress = new CheckForLongPress();
15492            }
15493            mPendingCheckForLongPress.rememberWindowAttachCount();
15494            postDelayed(mPendingCheckForLongPress,
15495                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15496        }
15497    }
15498
15499    /**
15500     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15501     * LayoutInflater} class, which provides a full range of options for view inflation.
15502     *
15503     * @param context The Context object for your activity or application.
15504     * @param resource The resource ID to inflate
15505     * @param root A view group that will be the parent.  Used to properly inflate the
15506     * layout_* parameters.
15507     * @see LayoutInflater
15508     */
15509    public static View inflate(Context context, int resource, ViewGroup root) {
15510        LayoutInflater factory = LayoutInflater.from(context);
15511        return factory.inflate(resource, root);
15512    }
15513
15514    /**
15515     * Scroll the view with standard behavior for scrolling beyond the normal
15516     * content boundaries. Views that call this method should override
15517     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15518     * results of an over-scroll operation.
15519     *
15520     * Views can use this method to handle any touch or fling-based scrolling.
15521     *
15522     * @param deltaX Change in X in pixels
15523     * @param deltaY Change in Y in pixels
15524     * @param scrollX Current X scroll value in pixels before applying deltaX
15525     * @param scrollY Current Y scroll value in pixels before applying deltaY
15526     * @param scrollRangeX Maximum content scroll range along the X axis
15527     * @param scrollRangeY Maximum content scroll range along the Y axis
15528     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15529     *          along the X axis.
15530     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15531     *          along the Y axis.
15532     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15533     * @return true if scrolling was clamped to an over-scroll boundary along either
15534     *          axis, false otherwise.
15535     */
15536    @SuppressWarnings({"UnusedParameters"})
15537    protected boolean overScrollBy(int deltaX, int deltaY,
15538            int scrollX, int scrollY,
15539            int scrollRangeX, int scrollRangeY,
15540            int maxOverScrollX, int maxOverScrollY,
15541            boolean isTouchEvent) {
15542        final int overScrollMode = mOverScrollMode;
15543        final boolean canScrollHorizontal =
15544                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15545        final boolean canScrollVertical =
15546                computeVerticalScrollRange() > computeVerticalScrollExtent();
15547        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15548                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15549        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15550                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15551
15552        int newScrollX = scrollX + deltaX;
15553        if (!overScrollHorizontal) {
15554            maxOverScrollX = 0;
15555        }
15556
15557        int newScrollY = scrollY + deltaY;
15558        if (!overScrollVertical) {
15559            maxOverScrollY = 0;
15560        }
15561
15562        // Clamp values if at the limits and record
15563        final int left = -maxOverScrollX;
15564        final int right = maxOverScrollX + scrollRangeX;
15565        final int top = -maxOverScrollY;
15566        final int bottom = maxOverScrollY + scrollRangeY;
15567
15568        boolean clampedX = false;
15569        if (newScrollX > right) {
15570            newScrollX = right;
15571            clampedX = true;
15572        } else if (newScrollX < left) {
15573            newScrollX = left;
15574            clampedX = true;
15575        }
15576
15577        boolean clampedY = false;
15578        if (newScrollY > bottom) {
15579            newScrollY = bottom;
15580            clampedY = true;
15581        } else if (newScrollY < top) {
15582            newScrollY = top;
15583            clampedY = true;
15584        }
15585
15586        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15587
15588        return clampedX || clampedY;
15589    }
15590
15591    /**
15592     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15593     * respond to the results of an over-scroll operation.
15594     *
15595     * @param scrollX New X scroll value in pixels
15596     * @param scrollY New Y scroll value in pixels
15597     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15598     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15599     */
15600    protected void onOverScrolled(int scrollX, int scrollY,
15601            boolean clampedX, boolean clampedY) {
15602        // Intentionally empty.
15603    }
15604
15605    /**
15606     * Returns the over-scroll mode for this view. The result will be
15607     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15608     * (allow over-scrolling only if the view content is larger than the container),
15609     * or {@link #OVER_SCROLL_NEVER}.
15610     *
15611     * @return This view's over-scroll mode.
15612     */
15613    public int getOverScrollMode() {
15614        return mOverScrollMode;
15615    }
15616
15617    /**
15618     * Set the over-scroll mode for this view. Valid over-scroll modes are
15619     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15620     * (allow over-scrolling only if the view content is larger than the container),
15621     * or {@link #OVER_SCROLL_NEVER}.
15622     *
15623     * Setting the over-scroll mode of a view will have an effect only if the
15624     * view is capable of scrolling.
15625     *
15626     * @param overScrollMode The new over-scroll mode for this view.
15627     */
15628    public void setOverScrollMode(int overScrollMode) {
15629        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15630                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15631                overScrollMode != OVER_SCROLL_NEVER) {
15632            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15633        }
15634        mOverScrollMode = overScrollMode;
15635    }
15636
15637    /**
15638     * Gets a scale factor that determines the distance the view should scroll
15639     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15640     * @return The vertical scroll scale factor.
15641     * @hide
15642     */
15643    protected float getVerticalScrollFactor() {
15644        if (mVerticalScrollFactor == 0) {
15645            TypedValue outValue = new TypedValue();
15646            if (!mContext.getTheme().resolveAttribute(
15647                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15648                throw new IllegalStateException(
15649                        "Expected theme to define listPreferredItemHeight.");
15650            }
15651            mVerticalScrollFactor = outValue.getDimension(
15652                    mContext.getResources().getDisplayMetrics());
15653        }
15654        return mVerticalScrollFactor;
15655    }
15656
15657    /**
15658     * Gets a scale factor that determines the distance the view should scroll
15659     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15660     * @return The horizontal scroll scale factor.
15661     * @hide
15662     */
15663    protected float getHorizontalScrollFactor() {
15664        // TODO: Should use something else.
15665        return getVerticalScrollFactor();
15666    }
15667
15668    /**
15669     * Return the value specifying the text direction or policy that was set with
15670     * {@link #setTextDirection(int)}.
15671     *
15672     * @return the defined text direction. It can be one of:
15673     *
15674     * {@link #TEXT_DIRECTION_INHERIT},
15675     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15676     * {@link #TEXT_DIRECTION_ANY_RTL},
15677     * {@link #TEXT_DIRECTION_LTR},
15678     * {@link #TEXT_DIRECTION_RTL},
15679     * {@link #TEXT_DIRECTION_LOCALE}
15680     */
15681    @ViewDebug.ExportedProperty(category = "text", mapping = {
15682            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
15683            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
15684            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
15685            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
15686            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
15687            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
15688    })
15689    public int getTextDirection() {
15690        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
15691    }
15692
15693    /**
15694     * Set the text direction.
15695     *
15696     * @param textDirection the direction to set. Should be one of:
15697     *
15698     * {@link #TEXT_DIRECTION_INHERIT},
15699     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15700     * {@link #TEXT_DIRECTION_ANY_RTL},
15701     * {@link #TEXT_DIRECTION_LTR},
15702     * {@link #TEXT_DIRECTION_RTL},
15703     * {@link #TEXT_DIRECTION_LOCALE}
15704     */
15705    public void setTextDirection(int textDirection) {
15706        if (getTextDirection() != textDirection) {
15707            // Reset the current text direction and the resolved one
15708            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
15709            resetResolvedTextDirection();
15710            // Set the new text direction
15711            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
15712            // Refresh
15713            requestLayout();
15714            invalidate(true);
15715        }
15716    }
15717
15718    /**
15719     * Return the resolved text direction.
15720     *
15721     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
15722     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
15723     * up the parent chain of the view. if there is no parent, then it will return the default
15724     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
15725     *
15726     * @return the resolved text direction. Returns one of:
15727     *
15728     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15729     * {@link #TEXT_DIRECTION_ANY_RTL},
15730     * {@link #TEXT_DIRECTION_LTR},
15731     * {@link #TEXT_DIRECTION_RTL},
15732     * {@link #TEXT_DIRECTION_LOCALE}
15733     */
15734    public int getResolvedTextDirection() {
15735        // The text direction will be resolved only if needed
15736        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
15737            resolveTextDirection();
15738        }
15739        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
15740    }
15741
15742    /**
15743     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
15744     * resolution is done.
15745     */
15746    public void resolveTextDirection() {
15747        // Reset any previous text direction resolution
15748        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15749
15750        if (hasRtlSupport()) {
15751            // Set resolved text direction flag depending on text direction flag
15752            final int textDirection = getTextDirection();
15753            switch(textDirection) {
15754                case TEXT_DIRECTION_INHERIT:
15755                    if (canResolveTextDirection()) {
15756                        ViewGroup viewGroup = ((ViewGroup) mParent);
15757
15758                        // Set current resolved direction to the same value as the parent's one
15759                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
15760                        switch (parentResolvedDirection) {
15761                            case TEXT_DIRECTION_FIRST_STRONG:
15762                            case TEXT_DIRECTION_ANY_RTL:
15763                            case TEXT_DIRECTION_LTR:
15764                            case TEXT_DIRECTION_RTL:
15765                            case TEXT_DIRECTION_LOCALE:
15766                                mPrivateFlags2 |=
15767                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15768                                break;
15769                            default:
15770                                // Default resolved direction is "first strong" heuristic
15771                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15772                        }
15773                    } else {
15774                        // We cannot do the resolution if there is no parent, so use the default one
15775                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15776                    }
15777                    break;
15778                case TEXT_DIRECTION_FIRST_STRONG:
15779                case TEXT_DIRECTION_ANY_RTL:
15780                case TEXT_DIRECTION_LTR:
15781                case TEXT_DIRECTION_RTL:
15782                case TEXT_DIRECTION_LOCALE:
15783                    // Resolved direction is the same as text direction
15784                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15785                    break;
15786                default:
15787                    // Default resolved direction is "first strong" heuristic
15788                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15789            }
15790        } else {
15791            // Default resolved direction is "first strong" heuristic
15792            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15793        }
15794
15795        // Set to resolved
15796        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
15797        onResolvedTextDirectionChanged();
15798    }
15799
15800    /**
15801     * Called when text direction has been resolved. Subclasses that care about text direction
15802     * resolution should override this method.
15803     *
15804     * The default implementation does nothing.
15805     */
15806    public void onResolvedTextDirectionChanged() {
15807    }
15808
15809    /**
15810     * Check if text direction resolution can be done.
15811     *
15812     * @return true if text direction resolution can be done otherwise return false.
15813     */
15814    public boolean canResolveTextDirection() {
15815        switch (getTextDirection()) {
15816            case TEXT_DIRECTION_INHERIT:
15817                return (mParent != null) && (mParent instanceof ViewGroup);
15818            default:
15819                return true;
15820        }
15821    }
15822
15823    /**
15824     * Reset resolved text direction. Text direction can be resolved with a call to
15825     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
15826     * reset is done.
15827     */
15828    public void resetResolvedTextDirection() {
15829        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15830        onResolvedTextDirectionReset();
15831    }
15832
15833    /**
15834     * Called when text direction is reset. Subclasses that care about text direction reset should
15835     * override this method and do a reset of the text direction of their children. The default
15836     * implementation does nothing.
15837     */
15838    public void onResolvedTextDirectionReset() {
15839    }
15840
15841    /**
15842     * Return the value specifying the text alignment or policy that was set with
15843     * {@link #setTextAlignment(int)}.
15844     *
15845     * @return the defined text alignment. It can be one of:
15846     *
15847     * {@link #TEXT_ALIGNMENT_INHERIT},
15848     * {@link #TEXT_ALIGNMENT_GRAVITY},
15849     * {@link #TEXT_ALIGNMENT_CENTER},
15850     * {@link #TEXT_ALIGNMENT_TEXT_START},
15851     * {@link #TEXT_ALIGNMENT_TEXT_END},
15852     * {@link #TEXT_ALIGNMENT_VIEW_START},
15853     * {@link #TEXT_ALIGNMENT_VIEW_END}
15854     */
15855    @ViewDebug.ExportedProperty(category = "text", mapping = {
15856            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15857            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15858            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15859            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15860            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15861            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15862            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15863    })
15864    public int getTextAlignment() {
15865        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
15866    }
15867
15868    /**
15869     * Set the text alignment.
15870     *
15871     * @param textAlignment The text alignment to set. Should be one of
15872     *
15873     * {@link #TEXT_ALIGNMENT_INHERIT},
15874     * {@link #TEXT_ALIGNMENT_GRAVITY},
15875     * {@link #TEXT_ALIGNMENT_CENTER},
15876     * {@link #TEXT_ALIGNMENT_TEXT_START},
15877     * {@link #TEXT_ALIGNMENT_TEXT_END},
15878     * {@link #TEXT_ALIGNMENT_VIEW_START},
15879     * {@link #TEXT_ALIGNMENT_VIEW_END}
15880     *
15881     * @attr ref android.R.styleable#View_textAlignment
15882     */
15883    public void setTextAlignment(int textAlignment) {
15884        if (textAlignment != getTextAlignment()) {
15885            // Reset the current and resolved text alignment
15886            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
15887            resetResolvedTextAlignment();
15888            // Set the new text alignment
15889            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
15890            // Refresh
15891            requestLayout();
15892            invalidate(true);
15893        }
15894    }
15895
15896    /**
15897     * Return the resolved text alignment.
15898     *
15899     * The resolved text alignment. This needs resolution if the value is
15900     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
15901     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
15902     *
15903     * @return the resolved text alignment. Returns one of:
15904     *
15905     * {@link #TEXT_ALIGNMENT_GRAVITY},
15906     * {@link #TEXT_ALIGNMENT_CENTER},
15907     * {@link #TEXT_ALIGNMENT_TEXT_START},
15908     * {@link #TEXT_ALIGNMENT_TEXT_END},
15909     * {@link #TEXT_ALIGNMENT_VIEW_START},
15910     * {@link #TEXT_ALIGNMENT_VIEW_END}
15911     */
15912    @ViewDebug.ExportedProperty(category = "text", mapping = {
15913            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15914            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15915            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15916            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15917            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15918            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15919            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15920    })
15921    public int getResolvedTextAlignment() {
15922        // If text alignment is not resolved, then resolve it
15923        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
15924            resolveTextAlignment();
15925        }
15926        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
15927    }
15928
15929    /**
15930     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
15931     * resolution is done.
15932     */
15933    public void resolveTextAlignment() {
15934        // Reset any previous text alignment resolution
15935        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
15936
15937        if (hasRtlSupport()) {
15938            // Set resolved text alignment flag depending on text alignment flag
15939            final int textAlignment = getTextAlignment();
15940            switch (textAlignment) {
15941                case TEXT_ALIGNMENT_INHERIT:
15942                    // Check if we can resolve the text alignment
15943                    if (canResolveLayoutDirection() && mParent instanceof View) {
15944                        View view = (View) mParent;
15945
15946                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
15947                        switch (parentResolvedTextAlignment) {
15948                            case TEXT_ALIGNMENT_GRAVITY:
15949                            case TEXT_ALIGNMENT_TEXT_START:
15950                            case TEXT_ALIGNMENT_TEXT_END:
15951                            case TEXT_ALIGNMENT_CENTER:
15952                            case TEXT_ALIGNMENT_VIEW_START:
15953                            case TEXT_ALIGNMENT_VIEW_END:
15954                                // Resolved text alignment is the same as the parent resolved
15955                                // text alignment
15956                                mPrivateFlags2 |=
15957                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
15958                                break;
15959                            default:
15960                                // Use default resolved text alignment
15961                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15962                        }
15963                    }
15964                    else {
15965                        // We cannot do the resolution if there is no parent so use the default
15966                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15967                    }
15968                    break;
15969                case TEXT_ALIGNMENT_GRAVITY:
15970                case TEXT_ALIGNMENT_TEXT_START:
15971                case TEXT_ALIGNMENT_TEXT_END:
15972                case TEXT_ALIGNMENT_CENTER:
15973                case TEXT_ALIGNMENT_VIEW_START:
15974                case TEXT_ALIGNMENT_VIEW_END:
15975                    // Resolved text alignment is the same as text alignment
15976                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
15977                    break;
15978                default:
15979                    // Use default resolved text alignment
15980                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15981            }
15982        } else {
15983            // Use default resolved text alignment
15984            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
15985        }
15986
15987        // Set the resolved
15988        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
15989        onResolvedTextAlignmentChanged();
15990    }
15991
15992    /**
15993     * Check if text alignment resolution can be done.
15994     *
15995     * @return true if text alignment resolution can be done otherwise return false.
15996     */
15997    public boolean canResolveTextAlignment() {
15998        switch (getTextAlignment()) {
15999            case TEXT_DIRECTION_INHERIT:
16000                return (mParent != null);
16001            default:
16002                return true;
16003        }
16004    }
16005
16006    /**
16007     * Called when text alignment has been resolved. Subclasses that care about text alignment
16008     * resolution should override this method.
16009     *
16010     * The default implementation does nothing.
16011     */
16012    public void onResolvedTextAlignmentChanged() {
16013    }
16014
16015    /**
16016     * Reset resolved text alignment. Text alignment can be resolved with a call to
16017     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16018     * reset is done.
16019     */
16020    public void resetResolvedTextAlignment() {
16021        // Reset any previous text alignment resolution
16022        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16023        onResolvedTextAlignmentReset();
16024    }
16025
16026    /**
16027     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16028     * override this method and do a reset of the text alignment of their children. The default
16029     * implementation does nothing.
16030     */
16031    public void onResolvedTextAlignmentReset() {
16032    }
16033
16034    //
16035    // Properties
16036    //
16037    /**
16038     * A Property wrapper around the <code>alpha</code> functionality handled by the
16039     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16040     */
16041    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16042        @Override
16043        public void setValue(View object, float value) {
16044            object.setAlpha(value);
16045        }
16046
16047        @Override
16048        public Float get(View object) {
16049            return object.getAlpha();
16050        }
16051    };
16052
16053    /**
16054     * A Property wrapper around the <code>translationX</code> functionality handled by the
16055     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16056     */
16057    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16058        @Override
16059        public void setValue(View object, float value) {
16060            object.setTranslationX(value);
16061        }
16062
16063                @Override
16064        public Float get(View object) {
16065            return object.getTranslationX();
16066        }
16067    };
16068
16069    /**
16070     * A Property wrapper around the <code>translationY</code> functionality handled by the
16071     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16072     */
16073    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16074        @Override
16075        public void setValue(View object, float value) {
16076            object.setTranslationY(value);
16077        }
16078
16079        @Override
16080        public Float get(View object) {
16081            return object.getTranslationY();
16082        }
16083    };
16084
16085    /**
16086     * A Property wrapper around the <code>x</code> functionality handled by the
16087     * {@link View#setX(float)} and {@link View#getX()} methods.
16088     */
16089    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16090        @Override
16091        public void setValue(View object, float value) {
16092            object.setX(value);
16093        }
16094
16095        @Override
16096        public Float get(View object) {
16097            return object.getX();
16098        }
16099    };
16100
16101    /**
16102     * A Property wrapper around the <code>y</code> functionality handled by the
16103     * {@link View#setY(float)} and {@link View#getY()} methods.
16104     */
16105    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16106        @Override
16107        public void setValue(View object, float value) {
16108            object.setY(value);
16109        }
16110
16111        @Override
16112        public Float get(View object) {
16113            return object.getY();
16114        }
16115    };
16116
16117    /**
16118     * A Property wrapper around the <code>rotation</code> functionality handled by the
16119     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16120     */
16121    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16122        @Override
16123        public void setValue(View object, float value) {
16124            object.setRotation(value);
16125        }
16126
16127        @Override
16128        public Float get(View object) {
16129            return object.getRotation();
16130        }
16131    };
16132
16133    /**
16134     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16135     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16136     */
16137    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16138        @Override
16139        public void setValue(View object, float value) {
16140            object.setRotationX(value);
16141        }
16142
16143        @Override
16144        public Float get(View object) {
16145            return object.getRotationX();
16146        }
16147    };
16148
16149    /**
16150     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16151     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16152     */
16153    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16154        @Override
16155        public void setValue(View object, float value) {
16156            object.setRotationY(value);
16157        }
16158
16159        @Override
16160        public Float get(View object) {
16161            return object.getRotationY();
16162        }
16163    };
16164
16165    /**
16166     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16167     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16168     */
16169    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16170        @Override
16171        public void setValue(View object, float value) {
16172            object.setScaleX(value);
16173        }
16174
16175        @Override
16176        public Float get(View object) {
16177            return object.getScaleX();
16178        }
16179    };
16180
16181    /**
16182     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16183     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16184     */
16185    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16186        @Override
16187        public void setValue(View object, float value) {
16188            object.setScaleY(value);
16189        }
16190
16191        @Override
16192        public Float get(View object) {
16193            return object.getScaleY();
16194        }
16195    };
16196
16197    /**
16198     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16199     * Each MeasureSpec represents a requirement for either the width or the height.
16200     * A MeasureSpec is comprised of a size and a mode. There are three possible
16201     * modes:
16202     * <dl>
16203     * <dt>UNSPECIFIED</dt>
16204     * <dd>
16205     * The parent has not imposed any constraint on the child. It can be whatever size
16206     * it wants.
16207     * </dd>
16208     *
16209     * <dt>EXACTLY</dt>
16210     * <dd>
16211     * The parent has determined an exact size for the child. The child is going to be
16212     * given those bounds regardless of how big it wants to be.
16213     * </dd>
16214     *
16215     * <dt>AT_MOST</dt>
16216     * <dd>
16217     * The child can be as large as it wants up to the specified size.
16218     * </dd>
16219     * </dl>
16220     *
16221     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16222     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16223     */
16224    public static class MeasureSpec {
16225        private static final int MODE_SHIFT = 30;
16226        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16227
16228        /**
16229         * Measure specification mode: The parent has not imposed any constraint
16230         * on the child. It can be whatever size it wants.
16231         */
16232        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16233
16234        /**
16235         * Measure specification mode: The parent has determined an exact size
16236         * for the child. The child is going to be given those bounds regardless
16237         * of how big it wants to be.
16238         */
16239        public static final int EXACTLY     = 1 << MODE_SHIFT;
16240
16241        /**
16242         * Measure specification mode: The child can be as large as it wants up
16243         * to the specified size.
16244         */
16245        public static final int AT_MOST     = 2 << MODE_SHIFT;
16246
16247        /**
16248         * Creates a measure specification based on the supplied size and mode.
16249         *
16250         * The mode must always be one of the following:
16251         * <ul>
16252         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16253         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16254         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16255         * </ul>
16256         *
16257         * @param size the size of the measure specification
16258         * @param mode the mode of the measure specification
16259         * @return the measure specification based on size and mode
16260         */
16261        public static int makeMeasureSpec(int size, int mode) {
16262            return size + mode;
16263        }
16264
16265        /**
16266         * Extracts the mode from the supplied measure specification.
16267         *
16268         * @param measureSpec the measure specification to extract the mode from
16269         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16270         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16271         *         {@link android.view.View.MeasureSpec#EXACTLY}
16272         */
16273        public static int getMode(int measureSpec) {
16274            return (measureSpec & MODE_MASK);
16275        }
16276
16277        /**
16278         * Extracts the size from the supplied measure specification.
16279         *
16280         * @param measureSpec the measure specification to extract the size from
16281         * @return the size in pixels defined in the supplied measure specification
16282         */
16283        public static int getSize(int measureSpec) {
16284            return (measureSpec & ~MODE_MASK);
16285        }
16286
16287        /**
16288         * Returns a String representation of the specified measure
16289         * specification.
16290         *
16291         * @param measureSpec the measure specification to convert to a String
16292         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16293         */
16294        public static String toString(int measureSpec) {
16295            int mode = getMode(measureSpec);
16296            int size = getSize(measureSpec);
16297
16298            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16299
16300            if (mode == UNSPECIFIED)
16301                sb.append("UNSPECIFIED ");
16302            else if (mode == EXACTLY)
16303                sb.append("EXACTLY ");
16304            else if (mode == AT_MOST)
16305                sb.append("AT_MOST ");
16306            else
16307                sb.append(mode).append(" ");
16308
16309            sb.append(size);
16310            return sb.toString();
16311        }
16312    }
16313
16314    class CheckForLongPress implements Runnable {
16315
16316        private int mOriginalWindowAttachCount;
16317
16318        public void run() {
16319            if (isPressed() && (mParent != null)
16320                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16321                if (performLongClick()) {
16322                    mHasPerformedLongPress = true;
16323                }
16324            }
16325        }
16326
16327        public void rememberWindowAttachCount() {
16328            mOriginalWindowAttachCount = mWindowAttachCount;
16329        }
16330    }
16331
16332    private final class CheckForTap implements Runnable {
16333        public void run() {
16334            mPrivateFlags &= ~PREPRESSED;
16335            setPressed(true);
16336            checkForLongClick(ViewConfiguration.getTapTimeout());
16337        }
16338    }
16339
16340    private final class PerformClick implements Runnable {
16341        public void run() {
16342            performClick();
16343        }
16344    }
16345
16346    /** @hide */
16347    public void hackTurnOffWindowResizeAnim(boolean off) {
16348        mAttachInfo.mTurnOffWindowResizeAnim = off;
16349    }
16350
16351    /**
16352     * This method returns a ViewPropertyAnimator object, which can be used to animate
16353     * specific properties on this View.
16354     *
16355     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16356     */
16357    public ViewPropertyAnimator animate() {
16358        if (mAnimator == null) {
16359            mAnimator = new ViewPropertyAnimator(this);
16360        }
16361        return mAnimator;
16362    }
16363
16364    /**
16365     * Interface definition for a callback to be invoked when a key event is
16366     * dispatched to this view. The callback will be invoked before the key
16367     * event is given to the view.
16368     */
16369    public interface OnKeyListener {
16370        /**
16371         * Called when a key is dispatched to a view. This allows listeners to
16372         * get a chance to respond before the target view.
16373         *
16374         * @param v The view the key has been dispatched to.
16375         * @param keyCode The code for the physical key that was pressed
16376         * @param event The KeyEvent object containing full information about
16377         *        the event.
16378         * @return True if the listener has consumed the event, false otherwise.
16379         */
16380        boolean onKey(View v, int keyCode, KeyEvent event);
16381    }
16382
16383    /**
16384     * Interface definition for a callback to be invoked when a touch event is
16385     * dispatched to this view. The callback will be invoked before the touch
16386     * event is given to the view.
16387     */
16388    public interface OnTouchListener {
16389        /**
16390         * Called when a touch event is dispatched to a view. This allows listeners to
16391         * get a chance to respond before the target view.
16392         *
16393         * @param v The view the touch event has been dispatched to.
16394         * @param event The MotionEvent object containing full information about
16395         *        the event.
16396         * @return True if the listener has consumed the event, false otherwise.
16397         */
16398        boolean onTouch(View v, MotionEvent event);
16399    }
16400
16401    /**
16402     * Interface definition for a callback to be invoked when a hover event is
16403     * dispatched to this view. The callback will be invoked before the hover
16404     * event is given to the view.
16405     */
16406    public interface OnHoverListener {
16407        /**
16408         * Called when a hover event is dispatched to a view. This allows listeners to
16409         * get a chance to respond before the target view.
16410         *
16411         * @param v The view the hover event has been dispatched to.
16412         * @param event The MotionEvent object containing full information about
16413         *        the event.
16414         * @return True if the listener has consumed the event, false otherwise.
16415         */
16416        boolean onHover(View v, MotionEvent event);
16417    }
16418
16419    /**
16420     * Interface definition for a callback to be invoked when a generic motion event is
16421     * dispatched to this view. The callback will be invoked before the generic motion
16422     * event is given to the view.
16423     */
16424    public interface OnGenericMotionListener {
16425        /**
16426         * Called when a generic motion event is dispatched to a view. This allows listeners to
16427         * get a chance to respond before the target view.
16428         *
16429         * @param v The view the generic motion event has been dispatched to.
16430         * @param event The MotionEvent object containing full information about
16431         *        the event.
16432         * @return True if the listener has consumed the event, false otherwise.
16433         */
16434        boolean onGenericMotion(View v, MotionEvent event);
16435    }
16436
16437    /**
16438     * Interface definition for a callback to be invoked when a view has been clicked and held.
16439     */
16440    public interface OnLongClickListener {
16441        /**
16442         * Called when a view has been clicked and held.
16443         *
16444         * @param v The view that was clicked and held.
16445         *
16446         * @return true if the callback consumed the long click, false otherwise.
16447         */
16448        boolean onLongClick(View v);
16449    }
16450
16451    /**
16452     * Interface definition for a callback to be invoked when a drag is being dispatched
16453     * to this view.  The callback will be invoked before the hosting view's own
16454     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16455     * onDrag(event) behavior, it should return 'false' from this callback.
16456     *
16457     * <div class="special reference">
16458     * <h3>Developer Guides</h3>
16459     * <p>For a guide to implementing drag and drop features, read the
16460     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16461     * </div>
16462     */
16463    public interface OnDragListener {
16464        /**
16465         * Called when a drag event is dispatched to a view. This allows listeners
16466         * to get a chance to override base View behavior.
16467         *
16468         * @param v The View that received the drag event.
16469         * @param event The {@link android.view.DragEvent} object for the drag event.
16470         * @return {@code true} if the drag event was handled successfully, or {@code false}
16471         * if the drag event was not handled. Note that {@code false} will trigger the View
16472         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16473         */
16474        boolean onDrag(View v, DragEvent event);
16475    }
16476
16477    /**
16478     * Interface definition for a callback to be invoked when the focus state of
16479     * a view changed.
16480     */
16481    public interface OnFocusChangeListener {
16482        /**
16483         * Called when the focus state of a view has changed.
16484         *
16485         * @param v The view whose state has changed.
16486         * @param hasFocus The new focus state of v.
16487         */
16488        void onFocusChange(View v, boolean hasFocus);
16489    }
16490
16491    /**
16492     * Interface definition for a callback to be invoked when a view is clicked.
16493     */
16494    public interface OnClickListener {
16495        /**
16496         * Called when a view has been clicked.
16497         *
16498         * @param v The view that was clicked.
16499         */
16500        void onClick(View v);
16501    }
16502
16503    /**
16504     * Interface definition for a callback to be invoked when the context menu
16505     * for this view is being built.
16506     */
16507    public interface OnCreateContextMenuListener {
16508        /**
16509         * Called when the context menu for this view is being built. It is not
16510         * safe to hold onto the menu after this method returns.
16511         *
16512         * @param menu The context menu that is being built
16513         * @param v The view for which the context menu is being built
16514         * @param menuInfo Extra information about the item for which the
16515         *            context menu should be shown. This information will vary
16516         *            depending on the class of v.
16517         */
16518        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16519    }
16520
16521    /**
16522     * Interface definition for a callback to be invoked when the status bar changes
16523     * visibility.  This reports <strong>global</strong> changes to the system UI
16524     * state, not just what the application is requesting.
16525     *
16526     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16527     */
16528    public interface OnSystemUiVisibilityChangeListener {
16529        /**
16530         * Called when the status bar changes visibility because of a call to
16531         * {@link View#setSystemUiVisibility(int)}.
16532         *
16533         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
16534         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
16535         * <strong>global</strong> state of the UI visibility flags, not what your
16536         * app is currently applying.
16537         */
16538        public void onSystemUiVisibilityChange(int visibility);
16539    }
16540
16541    /**
16542     * Interface definition for a callback to be invoked when this view is attached
16543     * or detached from its window.
16544     */
16545    public interface OnAttachStateChangeListener {
16546        /**
16547         * Called when the view is attached to a window.
16548         * @param v The view that was attached
16549         */
16550        public void onViewAttachedToWindow(View v);
16551        /**
16552         * Called when the view is detached from a window.
16553         * @param v The view that was detached
16554         */
16555        public void onViewDetachedFromWindow(View v);
16556    }
16557
16558    private final class UnsetPressedState implements Runnable {
16559        public void run() {
16560            setPressed(false);
16561        }
16562    }
16563
16564    /**
16565     * Base class for derived classes that want to save and restore their own
16566     * state in {@link android.view.View#onSaveInstanceState()}.
16567     */
16568    public static class BaseSavedState extends AbsSavedState {
16569        /**
16570         * Constructor used when reading from a parcel. Reads the state of the superclass.
16571         *
16572         * @param source
16573         */
16574        public BaseSavedState(Parcel source) {
16575            super(source);
16576        }
16577
16578        /**
16579         * Constructor called by derived classes when creating their SavedState objects
16580         *
16581         * @param superState The state of the superclass of this view
16582         */
16583        public BaseSavedState(Parcelable superState) {
16584            super(superState);
16585        }
16586
16587        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16588                new Parcelable.Creator<BaseSavedState>() {
16589            public BaseSavedState createFromParcel(Parcel in) {
16590                return new BaseSavedState(in);
16591            }
16592
16593            public BaseSavedState[] newArray(int size) {
16594                return new BaseSavedState[size];
16595            }
16596        };
16597    }
16598
16599    /**
16600     * A set of information given to a view when it is attached to its parent
16601     * window.
16602     */
16603    static class AttachInfo {
16604        interface Callbacks {
16605            void playSoundEffect(int effectId);
16606            boolean performHapticFeedback(int effectId, boolean always);
16607        }
16608
16609        /**
16610         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16611         * to a Handler. This class contains the target (View) to invalidate and
16612         * the coordinates of the dirty rectangle.
16613         *
16614         * For performance purposes, this class also implements a pool of up to
16615         * POOL_LIMIT objects that get reused. This reduces memory allocations
16616         * whenever possible.
16617         */
16618        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16619            private static final int POOL_LIMIT = 10;
16620            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16621                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16622                        public InvalidateInfo newInstance() {
16623                            return new InvalidateInfo();
16624                        }
16625
16626                        public void onAcquired(InvalidateInfo element) {
16627                        }
16628
16629                        public void onReleased(InvalidateInfo element) {
16630                            element.target = null;
16631                        }
16632                    }, POOL_LIMIT)
16633            );
16634
16635            private InvalidateInfo mNext;
16636            private boolean mIsPooled;
16637
16638            View target;
16639
16640            int left;
16641            int top;
16642            int right;
16643            int bottom;
16644
16645            public void setNextPoolable(InvalidateInfo element) {
16646                mNext = element;
16647            }
16648
16649            public InvalidateInfo getNextPoolable() {
16650                return mNext;
16651            }
16652
16653            static InvalidateInfo acquire() {
16654                return sPool.acquire();
16655            }
16656
16657            void release() {
16658                sPool.release(this);
16659            }
16660
16661            public boolean isPooled() {
16662                return mIsPooled;
16663            }
16664
16665            public void setPooled(boolean isPooled) {
16666                mIsPooled = isPooled;
16667            }
16668        }
16669
16670        final IWindowSession mSession;
16671
16672        final IWindow mWindow;
16673
16674        final IBinder mWindowToken;
16675
16676        final Callbacks mRootCallbacks;
16677
16678        HardwareCanvas mHardwareCanvas;
16679
16680        /**
16681         * The top view of the hierarchy.
16682         */
16683        View mRootView;
16684
16685        IBinder mPanelParentWindowToken;
16686        Surface mSurface;
16687
16688        boolean mHardwareAccelerated;
16689        boolean mHardwareAccelerationRequested;
16690        HardwareRenderer mHardwareRenderer;
16691
16692        boolean mScreenOn;
16693
16694        /**
16695         * Scale factor used by the compatibility mode
16696         */
16697        float mApplicationScale;
16698
16699        /**
16700         * Indicates whether the application is in compatibility mode
16701         */
16702        boolean mScalingRequired;
16703
16704        /**
16705         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
16706         */
16707        boolean mTurnOffWindowResizeAnim;
16708
16709        /**
16710         * Left position of this view's window
16711         */
16712        int mWindowLeft;
16713
16714        /**
16715         * Top position of this view's window
16716         */
16717        int mWindowTop;
16718
16719        /**
16720         * Indicates whether views need to use 32-bit drawing caches
16721         */
16722        boolean mUse32BitDrawingCache;
16723
16724        /**
16725         * For windows that are full-screen but using insets to layout inside
16726         * of the screen decorations, these are the current insets for the
16727         * content of the window.
16728         */
16729        final Rect mContentInsets = new Rect();
16730
16731        /**
16732         * For windows that are full-screen but using insets to layout inside
16733         * of the screen decorations, these are the current insets for the
16734         * actual visible parts of the window.
16735         */
16736        final Rect mVisibleInsets = new Rect();
16737
16738        /**
16739         * The internal insets given by this window.  This value is
16740         * supplied by the client (through
16741         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
16742         * be given to the window manager when changed to be used in laying
16743         * out windows behind it.
16744         */
16745        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
16746                = new ViewTreeObserver.InternalInsetsInfo();
16747
16748        /**
16749         * All views in the window's hierarchy that serve as scroll containers,
16750         * used to determine if the window can be resized or must be panned
16751         * to adjust for a soft input area.
16752         */
16753        final ArrayList<View> mScrollContainers = new ArrayList<View>();
16754
16755        final KeyEvent.DispatcherState mKeyDispatchState
16756                = new KeyEvent.DispatcherState();
16757
16758        /**
16759         * Indicates whether the view's window currently has the focus.
16760         */
16761        boolean mHasWindowFocus;
16762
16763        /**
16764         * The current visibility of the window.
16765         */
16766        int mWindowVisibility;
16767
16768        /**
16769         * Indicates the time at which drawing started to occur.
16770         */
16771        long mDrawingTime;
16772
16773        /**
16774         * Indicates whether or not ignoring the DIRTY_MASK flags.
16775         */
16776        boolean mIgnoreDirtyState;
16777
16778        /**
16779         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
16780         * to avoid clearing that flag prematurely.
16781         */
16782        boolean mSetIgnoreDirtyState = false;
16783
16784        /**
16785         * Indicates whether the view's window is currently in touch mode.
16786         */
16787        boolean mInTouchMode;
16788
16789        /**
16790         * Indicates that ViewAncestor should trigger a global layout change
16791         * the next time it performs a traversal
16792         */
16793        boolean mRecomputeGlobalAttributes;
16794
16795        /**
16796         * Always report new attributes at next traversal.
16797         */
16798        boolean mForceReportNewAttributes;
16799
16800        /**
16801         * Set during a traveral if any views want to keep the screen on.
16802         */
16803        boolean mKeepScreenOn;
16804
16805        /**
16806         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
16807         */
16808        int mSystemUiVisibility;
16809
16810        /**
16811         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
16812         * attached.
16813         */
16814        boolean mHasSystemUiListeners;
16815
16816        /**
16817         * Set if the visibility of any views has changed.
16818         */
16819        boolean mViewVisibilityChanged;
16820
16821        /**
16822         * Set to true if a view has been scrolled.
16823         */
16824        boolean mViewScrollChanged;
16825
16826        /**
16827         * Global to the view hierarchy used as a temporary for dealing with
16828         * x/y points in the transparent region computations.
16829         */
16830        final int[] mTransparentLocation = new int[2];
16831
16832        /**
16833         * Global to the view hierarchy used as a temporary for dealing with
16834         * x/y points in the ViewGroup.invalidateChild implementation.
16835         */
16836        final int[] mInvalidateChildLocation = new int[2];
16837
16838
16839        /**
16840         * Global to the view hierarchy used as a temporary for dealing with
16841         * x/y location when view is transformed.
16842         */
16843        final float[] mTmpTransformLocation = new float[2];
16844
16845        /**
16846         * The view tree observer used to dispatch global events like
16847         * layout, pre-draw, touch mode change, etc.
16848         */
16849        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
16850
16851        /**
16852         * A Canvas used by the view hierarchy to perform bitmap caching.
16853         */
16854        Canvas mCanvas;
16855
16856        /**
16857         * The view root impl.
16858         */
16859        final ViewRootImpl mViewRootImpl;
16860
16861        /**
16862         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
16863         * handler can be used to pump events in the UI events queue.
16864         */
16865        final Handler mHandler;
16866
16867        /**
16868         * Temporary for use in computing invalidate rectangles while
16869         * calling up the hierarchy.
16870         */
16871        final Rect mTmpInvalRect = new Rect();
16872
16873        /**
16874         * Temporary for use in computing hit areas with transformed views
16875         */
16876        final RectF mTmpTransformRect = new RectF();
16877
16878        /**
16879         * Temporary list for use in collecting focusable descendents of a view.
16880         */
16881        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
16882
16883        /**
16884         * The id of the window for accessibility purposes.
16885         */
16886        int mAccessibilityWindowId = View.NO_ID;
16887
16888        /**
16889         * Whether to ingore not exposed for accessibility Views when
16890         * reporting the view tree to accessibility services.
16891         */
16892        boolean mIncludeNotImportantViews;
16893
16894        /**
16895         * The drawable for highlighting accessibility focus.
16896         */
16897        Drawable mAccessibilityFocusDrawable;
16898
16899        /**
16900         * Creates a new set of attachment information with the specified
16901         * events handler and thread.
16902         *
16903         * @param handler the events handler the view must use
16904         */
16905        AttachInfo(IWindowSession session, IWindow window,
16906                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
16907            mSession = session;
16908            mWindow = window;
16909            mWindowToken = window.asBinder();
16910            mViewRootImpl = viewRootImpl;
16911            mHandler = handler;
16912            mRootCallbacks = effectPlayer;
16913        }
16914    }
16915
16916    /**
16917     * <p>ScrollabilityCache holds various fields used by a View when scrolling
16918     * is supported. This avoids keeping too many unused fields in most
16919     * instances of View.</p>
16920     */
16921    private static class ScrollabilityCache implements Runnable {
16922
16923        /**
16924         * Scrollbars are not visible
16925         */
16926        public static final int OFF = 0;
16927
16928        /**
16929         * Scrollbars are visible
16930         */
16931        public static final int ON = 1;
16932
16933        /**
16934         * Scrollbars are fading away
16935         */
16936        public static final int FADING = 2;
16937
16938        public boolean fadeScrollBars;
16939
16940        public int fadingEdgeLength;
16941        public int scrollBarDefaultDelayBeforeFade;
16942        public int scrollBarFadeDuration;
16943
16944        public int scrollBarSize;
16945        public ScrollBarDrawable scrollBar;
16946        public float[] interpolatorValues;
16947        public View host;
16948
16949        public final Paint paint;
16950        public final Matrix matrix;
16951        public Shader shader;
16952
16953        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
16954
16955        private static final float[] OPAQUE = { 255 };
16956        private static final float[] TRANSPARENT = { 0.0f };
16957
16958        /**
16959         * When fading should start. This time moves into the future every time
16960         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
16961         */
16962        public long fadeStartTime;
16963
16964
16965        /**
16966         * The current state of the scrollbars: ON, OFF, or FADING
16967         */
16968        public int state = OFF;
16969
16970        private int mLastColor;
16971
16972        public ScrollabilityCache(ViewConfiguration configuration, View host) {
16973            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
16974            scrollBarSize = configuration.getScaledScrollBarSize();
16975            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
16976            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
16977
16978            paint = new Paint();
16979            matrix = new Matrix();
16980            // use use a height of 1, and then wack the matrix each time we
16981            // actually use it.
16982            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
16983
16984            paint.setShader(shader);
16985            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
16986            this.host = host;
16987        }
16988
16989        public void setFadeColor(int color) {
16990            if (color != 0 && color != mLastColor) {
16991                mLastColor = color;
16992                color |= 0xFF000000;
16993
16994                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
16995                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
16996
16997                paint.setShader(shader);
16998                // Restore the default transfer mode (src_over)
16999                paint.setXfermode(null);
17000            }
17001        }
17002
17003        public void run() {
17004            long now = AnimationUtils.currentAnimationTimeMillis();
17005            if (now >= fadeStartTime) {
17006
17007                // the animation fades the scrollbars out by changing
17008                // the opacity (alpha) from fully opaque to fully
17009                // transparent
17010                int nextFrame = (int) now;
17011                int framesCount = 0;
17012
17013                Interpolator interpolator = scrollBarInterpolator;
17014
17015                // Start opaque
17016                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17017
17018                // End transparent
17019                nextFrame += scrollBarFadeDuration;
17020                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17021
17022                state = FADING;
17023
17024                // Kick off the fade animation
17025                host.invalidate(true);
17026            }
17027        }
17028    }
17029
17030    /**
17031     * Resuable callback for sending
17032     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17033     */
17034    private class SendViewScrolledAccessibilityEvent implements Runnable {
17035        public volatile boolean mIsPending;
17036
17037        public void run() {
17038            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17039            mIsPending = false;
17040        }
17041    }
17042
17043    /**
17044     * <p>
17045     * This class represents a delegate that can be registered in a {@link View}
17046     * to enhance accessibility support via composition rather via inheritance.
17047     * It is specifically targeted to widget developers that extend basic View
17048     * classes i.e. classes in package android.view, that would like their
17049     * applications to be backwards compatible.
17050     * </p>
17051     * <div class="special reference">
17052     * <h3>Developer Guides</h3>
17053     * <p>For more information about making applications accessible, read the
17054     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17055     * developer guide.</p>
17056     * </div>
17057     * <p>
17058     * A scenario in which a developer would like to use an accessibility delegate
17059     * is overriding a method introduced in a later API version then the minimal API
17060     * version supported by the application. For example, the method
17061     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17062     * in API version 4 when the accessibility APIs were first introduced. If a
17063     * developer would like his application to run on API version 4 devices (assuming
17064     * all other APIs used by the application are version 4 or lower) and take advantage
17065     * of this method, instead of overriding the method which would break the application's
17066     * backwards compatibility, he can override the corresponding method in this
17067     * delegate and register the delegate in the target View if the API version of
17068     * the system is high enough i.e. the API version is same or higher to the API
17069     * version that introduced
17070     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17071     * </p>
17072     * <p>
17073     * Here is an example implementation:
17074     * </p>
17075     * <code><pre><p>
17076     * if (Build.VERSION.SDK_INT >= 14) {
17077     *     // If the API version is equal of higher than the version in
17078     *     // which onInitializeAccessibilityNodeInfo was introduced we
17079     *     // register a delegate with a customized implementation.
17080     *     View view = findViewById(R.id.view_id);
17081     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17082     *         public void onInitializeAccessibilityNodeInfo(View host,
17083     *                 AccessibilityNodeInfo info) {
17084     *             // Let the default implementation populate the info.
17085     *             super.onInitializeAccessibilityNodeInfo(host, info);
17086     *             // Set some other information.
17087     *             info.setEnabled(host.isEnabled());
17088     *         }
17089     *     });
17090     * }
17091     * </code></pre></p>
17092     * <p>
17093     * This delegate contains methods that correspond to the accessibility methods
17094     * in View. If a delegate has been specified the implementation in View hands
17095     * off handling to the corresponding method in this delegate. The default
17096     * implementation the delegate methods behaves exactly as the corresponding
17097     * method in View for the case of no accessibility delegate been set. Hence,
17098     * to customize the behavior of a View method, clients can override only the
17099     * corresponding delegate method without altering the behavior of the rest
17100     * accessibility related methods of the host view.
17101     * </p>
17102     */
17103    public static class AccessibilityDelegate {
17104
17105        /**
17106         * Sends an accessibility event of the given type. If accessibility is not
17107         * enabled this method has no effect.
17108         * <p>
17109         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17110         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17111         * been set.
17112         * </p>
17113         *
17114         * @param host The View hosting the delegate.
17115         * @param eventType The type of the event to send.
17116         *
17117         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17118         */
17119        public void sendAccessibilityEvent(View host, int eventType) {
17120            host.sendAccessibilityEventInternal(eventType);
17121        }
17122
17123        /**
17124         * Sends an accessibility event. This method behaves exactly as
17125         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17126         * empty {@link AccessibilityEvent} and does not perform a check whether
17127         * accessibility is enabled.
17128         * <p>
17129         * The default implementation behaves as
17130         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17131         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17132         * the case of no accessibility delegate been set.
17133         * </p>
17134         *
17135         * @param host The View hosting the delegate.
17136         * @param event The event to send.
17137         *
17138         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17139         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17140         */
17141        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17142            host.sendAccessibilityEventUncheckedInternal(event);
17143        }
17144
17145        /**
17146         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17147         * to its children for adding their text content to the event.
17148         * <p>
17149         * The default implementation behaves as
17150         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17151         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17152         * the case of no accessibility delegate been set.
17153         * </p>
17154         *
17155         * @param host The View hosting the delegate.
17156         * @param event The event.
17157         * @return True if the event population was completed.
17158         *
17159         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17160         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17161         */
17162        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17163            return host.dispatchPopulateAccessibilityEventInternal(event);
17164        }
17165
17166        /**
17167         * Gives a chance to the host View to populate the accessibility event with its
17168         * text content.
17169         * <p>
17170         * The default implementation behaves as
17171         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17172         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17173         * the case of no accessibility delegate been set.
17174         * </p>
17175         *
17176         * @param host The View hosting the delegate.
17177         * @param event The accessibility event which to populate.
17178         *
17179         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17180         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17181         */
17182        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17183            host.onPopulateAccessibilityEventInternal(event);
17184        }
17185
17186        /**
17187         * Initializes an {@link AccessibilityEvent} with information about the
17188         * the host View which is the event source.
17189         * <p>
17190         * The default implementation behaves as
17191         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17192         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17193         * the case of no accessibility delegate been set.
17194         * </p>
17195         *
17196         * @param host The View hosting the delegate.
17197         * @param event The event to initialize.
17198         *
17199         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17200         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17201         */
17202        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17203            host.onInitializeAccessibilityEventInternal(event);
17204        }
17205
17206        /**
17207         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17208         * <p>
17209         * The default implementation behaves as
17210         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17211         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17212         * the case of no accessibility delegate been set.
17213         * </p>
17214         *
17215         * @param host The View hosting the delegate.
17216         * @param info The instance to initialize.
17217         *
17218         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17219         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17220         */
17221        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17222            host.onInitializeAccessibilityNodeInfoInternal(info);
17223        }
17224
17225        /**
17226         * Called when a child of the host View has requested sending an
17227         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17228         * to augment the event.
17229         * <p>
17230         * The default implementation behaves as
17231         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17232         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17233         * the case of no accessibility delegate been set.
17234         * </p>
17235         *
17236         * @param host The View hosting the delegate.
17237         * @param child The child which requests sending the event.
17238         * @param event The event to be sent.
17239         * @return True if the event should be sent
17240         *
17241         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17242         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17243         */
17244        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17245                AccessibilityEvent event) {
17246            return host.onRequestSendAccessibilityEventInternal(child, event);
17247        }
17248
17249        /**
17250         * Gets the provider for managing a virtual view hierarchy rooted at this View
17251         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17252         * that explore the window content.
17253         * <p>
17254         * The default implementation behaves as
17255         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17256         * the case of no accessibility delegate been set.
17257         * </p>
17258         *
17259         * @return The provider.
17260         *
17261         * @see AccessibilityNodeProvider
17262         */
17263        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17264            return null;
17265        }
17266    }
17267}
17268