View.java revision 4fa22f0b4d271a41e2a459e1d927c4ce54d15847
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.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.SystemProperties;
50import android.text.TextUtils;
51import android.util.AttributeSet;
52import android.util.FloatProperty;
53import android.util.LocaleUtil;
54import android.util.Log;
55import android.util.Pool;
56import android.util.Poolable;
57import android.util.PoolableManager;
58import android.util.Pools;
59import android.util.Property;
60import android.util.SparseArray;
61import android.util.TypedValue;
62import android.view.ContextMenu.ContextMenuInfo;
63import android.view.accessibility.AccessibilityEvent;
64import android.view.accessibility.AccessibilityEventSource;
65import android.view.accessibility.AccessibilityManager;
66import android.view.accessibility.AccessibilityNodeInfo;
67import android.view.accessibility.AccessibilityNodeProvider;
68import android.view.animation.Animation;
69import android.view.animation.AnimationUtils;
70import android.view.animation.Transformation;
71import android.view.inputmethod.EditorInfo;
72import android.view.inputmethod.InputConnection;
73import android.view.inputmethod.InputMethodManager;
74import android.widget.ScrollBarDrawable;
75
76import static android.os.Build.VERSION_CODES.*;
77import static java.lang.Math.max;
78
79import com.android.internal.R;
80import com.android.internal.util.Predicate;
81import com.android.internal.view.menu.MenuBuilder;
82
83import java.lang.ref.WeakReference;
84import java.lang.reflect.InvocationTargetException;
85import java.lang.reflect.Method;
86import java.util.ArrayList;
87import java.util.Arrays;
88import java.util.Locale;
89import java.util.concurrent.CopyOnWriteArrayList;
90
91/**
92 * <p>
93 * This class represents the basic building block for user interface components. A View
94 * occupies a rectangular area on the screen and is responsible for drawing and
95 * event handling. View is the base class for <em>widgets</em>, which are
96 * used to create interactive UI components (buttons, text fields, etc.). The
97 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
98 * are invisible containers that hold other Views (or other ViewGroups) and define
99 * their layout properties.
100 * </p>
101 *
102 * <div class="special reference">
103 * <h3>Developer Guides</h3>
104 * <p>For information about using this class to develop your application's user interface,
105 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
106 * </div>
107 *
108 * <a name="Using"></a>
109 * <h3>Using Views</h3>
110 * <p>
111 * All of the views in a window are arranged in a single tree. You can add views
112 * either from code or by specifying a tree of views in one or more XML layout
113 * files. There are many specialized subclasses of views that act as controls or
114 * are capable of displaying text, images, or other content.
115 * </p>
116 * <p>
117 * Once you have created a tree of views, there are typically a few types of
118 * common operations you may wish to perform:
119 * <ul>
120 * <li><strong>Set properties:</strong> for example setting the text of a
121 * {@link android.widget.TextView}. The available properties and the methods
122 * that set them will vary among the different subclasses of views. Note that
123 * properties that are known at build time can be set in the XML layout
124 * files.</li>
125 * <li><strong>Set focus:</strong> The framework will handled moving focus in
126 * response to user input. To force focus to a specific view, call
127 * {@link #requestFocus}.</li>
128 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
129 * that will be notified when something interesting happens to the view. For
130 * example, all views will let you set a listener to be notified when the view
131 * gains or loses focus. You can register such a listener using
132 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
133 * Other view subclasses offer more specialized listeners. For example, a Button
134 * exposes a listener to notify clients when the button is clicked.</li>
135 * <li><strong>Set visibility:</strong> You can hide or show views using
136 * {@link #setVisibility(int)}.</li>
137 * </ul>
138 * </p>
139 * <p><em>
140 * Note: The Android framework is responsible for measuring, laying out and
141 * drawing views. You should not call methods that perform these actions on
142 * views yourself unless you are actually implementing a
143 * {@link android.view.ViewGroup}.
144 * </em></p>
145 *
146 * <a name="Lifecycle"></a>
147 * <h3>Implementing a Custom View</h3>
148 *
149 * <p>
150 * To implement a custom view, you will usually begin by providing overrides for
151 * some of the standard methods that the framework calls on all views. You do
152 * not need to override all of these methods. In fact, you can start by just
153 * overriding {@link #onDraw(android.graphics.Canvas)}.
154 * <table border="2" width="85%" align="center" cellpadding="5">
155 *     <thead>
156 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
157 *     </thead>
158 *
159 *     <tbody>
160 *     <tr>
161 *         <td rowspan="2">Creation</td>
162 *         <td>Constructors</td>
163 *         <td>There is a form of the constructor that are called when the view
164 *         is created from code and a form that is called when the view is
165 *         inflated from a layout file. The second form should parse and apply
166 *         any attributes defined in the layout file.
167 *         </td>
168 *     </tr>
169 *     <tr>
170 *         <td><code>{@link #onFinishInflate()}</code></td>
171 *         <td>Called after a view and all of its children has been inflated
172 *         from XML.</td>
173 *     </tr>
174 *
175 *     <tr>
176 *         <td rowspan="3">Layout</td>
177 *         <td><code>{@link #onMeasure(int, int)}</code></td>
178 *         <td>Called to determine the size requirements for this view and all
179 *         of its children.
180 *         </td>
181 *     </tr>
182 *     <tr>
183 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
184 *         <td>Called when this view should assign a size and position to all
185 *         of its children.
186 *         </td>
187 *     </tr>
188 *     <tr>
189 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
190 *         <td>Called when the size of this view has changed.
191 *         </td>
192 *     </tr>
193 *
194 *     <tr>
195 *         <td>Drawing</td>
196 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
197 *         <td>Called when the view should render its content.
198 *         </td>
199 *     </tr>
200 *
201 *     <tr>
202 *         <td rowspan="4">Event processing</td>
203 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
204 *         <td>Called when a new key event occurs.
205 *         </td>
206 *     </tr>
207 *     <tr>
208 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
209 *         <td>Called when a key up event occurs.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
214 *         <td>Called when a trackball motion event occurs.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
219 *         <td>Called when a touch screen motion event occurs.
220 *         </td>
221 *     </tr>
222 *
223 *     <tr>
224 *         <td rowspan="2">Focus</td>
225 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
226 *         <td>Called when the view gains or loses focus.
227 *         </td>
228 *     </tr>
229 *
230 *     <tr>
231 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
232 *         <td>Called when the window containing the view gains or loses focus.
233 *         </td>
234 *     </tr>
235 *
236 *     <tr>
237 *         <td rowspan="3">Attaching</td>
238 *         <td><code>{@link #onAttachedToWindow()}</code></td>
239 *         <td>Called when the view is attached to a window.
240 *         </td>
241 *     </tr>
242 *
243 *     <tr>
244 *         <td><code>{@link #onDetachedFromWindow}</code></td>
245 *         <td>Called when the view is detached from its window.
246 *         </td>
247 *     </tr>
248 *
249 *     <tr>
250 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
251 *         <td>Called when the visibility of the window containing the view
252 *         has changed.
253 *         </td>
254 *     </tr>
255 *     </tbody>
256 *
257 * </table>
258 * </p>
259 *
260 * <a name="IDs"></a>
261 * <h3>IDs</h3>
262 * Views may have an integer id associated with them. These ids are typically
263 * assigned in the layout XML files, and are used to find specific views within
264 * the view tree. A common pattern is to:
265 * <ul>
266 * <li>Define a Button in the layout file and assign it a unique ID.
267 * <pre>
268 * &lt;Button
269 *     android:id="@+id/my_button"
270 *     android:layout_width="wrap_content"
271 *     android:layout_height="wrap_content"
272 *     android:text="@string/my_button_text"/&gt;
273 * </pre></li>
274 * <li>From the onCreate method of an Activity, find the Button
275 * <pre class="prettyprint">
276 *      Button myButton = (Button) findViewById(R.id.my_button);
277 * </pre></li>
278 * </ul>
279 * <p>
280 * View IDs need not be unique throughout the tree, but it is good practice to
281 * ensure that they are at least unique within the part of the tree you are
282 * searching.
283 * </p>
284 *
285 * <a name="Position"></a>
286 * <h3>Position</h3>
287 * <p>
288 * The geometry of a view is that of a rectangle. A view has a location,
289 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
290 * two dimensions, expressed as a width and a height. The unit for location
291 * and dimensions is the pixel.
292 * </p>
293 *
294 * <p>
295 * It is possible to retrieve the location of a view by invoking the methods
296 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
297 * coordinate of the rectangle representing the view. The latter returns the
298 * top, or Y, coordinate of the rectangle representing the view. These methods
299 * both return the location of the view relative to its parent. For instance,
300 * when getLeft() returns 20, that means the view is located 20 pixels to the
301 * right of the left edge of its direct parent.
302 * </p>
303 *
304 * <p>
305 * In addition, several convenience methods are offered to avoid unnecessary
306 * computations, namely {@link #getRight()} and {@link #getBottom()}.
307 * These methods return the coordinates of the right and bottom edges of the
308 * rectangle representing the view. For instance, calling {@link #getRight()}
309 * is similar to the following computation: <code>getLeft() + getWidth()</code>
310 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
311 * </p>
312 *
313 * <a name="SizePaddingMargins"></a>
314 * <h3>Size, padding and margins</h3>
315 * <p>
316 * The size of a view is expressed with a width and a height. A view actually
317 * possess two pairs of width and height values.
318 * </p>
319 *
320 * <p>
321 * The first pair is known as <em>measured width</em> and
322 * <em>measured height</em>. These dimensions define how big a view wants to be
323 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
324 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
325 * and {@link #getMeasuredHeight()}.
326 * </p>
327 *
328 * <p>
329 * The second pair is simply known as <em>width</em> and <em>height</em>, or
330 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
331 * dimensions define the actual size of the view on screen, at drawing time and
332 * after layout. These values may, but do not have to, be different from the
333 * measured width and height. The width and height can be obtained by calling
334 * {@link #getWidth()} and {@link #getHeight()}.
335 * </p>
336 *
337 * <p>
338 * To measure its dimensions, a view takes into account its padding. The padding
339 * is expressed in pixels for the left, top, right and bottom parts of the view.
340 * Padding can be used to offset the content of the view by a specific amount of
341 * pixels. For instance, a left padding of 2 will push the view's content by
342 * 2 pixels to the right of the left edge. Padding can be set using the
343 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
344 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
345 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
346 * {@link #getPaddingEnd()}.
347 * </p>
348 *
349 * <p>
350 * Even though a view can define a padding, it does not provide any support for
351 * margins. However, view groups provide such a support. Refer to
352 * {@link android.view.ViewGroup} and
353 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
354 * </p>
355 *
356 * <a name="Layout"></a>
357 * <h3>Layout</h3>
358 * <p>
359 * Layout is a two pass process: a measure pass and a layout pass. The measuring
360 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
361 * of the view tree. Each view pushes dimension specifications down the tree
362 * during the recursion. At the end of the measure pass, every view has stored
363 * its measurements. The second pass happens in
364 * {@link #layout(int,int,int,int)} and is also top-down. During
365 * this pass each parent is responsible for positioning all of its children
366 * using the sizes computed in the measure pass.
367 * </p>
368 *
369 * <p>
370 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
371 * {@link #getMeasuredHeight()} values must be set, along with those for all of
372 * that view's descendants. A view's measured width and measured height values
373 * must respect the constraints imposed by the view's parents. This guarantees
374 * that at the end of the measure pass, all parents accept all of their
375 * children's measurements. A parent view may call measure() more than once on
376 * its children. For example, the parent may measure each child once with
377 * unspecified dimensions to find out how big they want to be, then call
378 * measure() on them again with actual numbers if the sum of all the children's
379 * unconstrained sizes is too big or too small.
380 * </p>
381 *
382 * <p>
383 * The measure pass uses two classes to communicate dimensions. The
384 * {@link MeasureSpec} class is used by views to tell their parents how they
385 * want to be measured and positioned. The base LayoutParams class just
386 * describes how big the view wants to be for both width and height. For each
387 * dimension, it can specify one of:
388 * <ul>
389 * <li> an exact number
390 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
391 * (minus padding)
392 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
393 * enclose its content (plus padding).
394 * </ul>
395 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
396 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
397 * an X and Y value.
398 * </p>
399 *
400 * <p>
401 * MeasureSpecs are used to push requirements down the tree from parent to
402 * child. A MeasureSpec can be in one of three modes:
403 * <ul>
404 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
405 * of a child view. For example, a LinearLayout may call measure() on its child
406 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
407 * tall the child view wants to be given a width of 240 pixels.
408 * <li>EXACTLY: This is used by the parent to impose an exact size on the
409 * child. The child must use this size, and guarantee that all of its
410 * descendants will fit within this size.
411 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
412 * child. The child must gurantee that it and all of its descendants will fit
413 * within this size.
414 * </ul>
415 * </p>
416 *
417 * <p>
418 * To intiate a layout, call {@link #requestLayout}. This method is typically
419 * called by a view on itself when it believes that is can no longer fit within
420 * its current bounds.
421 * </p>
422 *
423 * <a name="Drawing"></a>
424 * <h3>Drawing</h3>
425 * <p>
426 * Drawing is handled by walking the tree and rendering each view that
427 * intersects the invalid region. Because the tree is traversed in-order,
428 * this means that parents will draw before (i.e., behind) their children, with
429 * siblings drawn in the order they appear in the tree.
430 * If you set a background drawable for a View, then the View will draw it for you
431 * before calling back to its <code>onDraw()</code> method.
432 * </p>
433 *
434 * <p>
435 * Note that the framework will not draw views that are not in the invalid region.
436 * </p>
437 *
438 * <p>
439 * To force a view to draw, call {@link #invalidate()}.
440 * </p>
441 *
442 * <a name="EventHandlingThreading"></a>
443 * <h3>Event Handling and Threading</h3>
444 * <p>
445 * The basic cycle of a view is as follows:
446 * <ol>
447 * <li>An event comes in and is dispatched to the appropriate view. The view
448 * handles the event and notifies any listeners.</li>
449 * <li>If in the course of processing the event, the view's bounds may need
450 * to be changed, the view will call {@link #requestLayout()}.</li>
451 * <li>Similarly, if in the course of processing the event the view's appearance
452 * may need to be changed, the view will call {@link #invalidate()}.</li>
453 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
454 * the framework will take care of measuring, laying out, and drawing the tree
455 * as appropriate.</li>
456 * </ol>
457 * </p>
458 *
459 * <p><em>Note: The entire view tree is single threaded. You must always be on
460 * the UI thread when calling any method on any view.</em>
461 * If you are doing work on other threads and want to update the state of a view
462 * from that thread, you should use a {@link Handler}.
463 * </p>
464 *
465 * <a name="FocusHandling"></a>
466 * <h3>Focus Handling</h3>
467 * <p>
468 * The framework will handle routine focus movement in response to user input.
469 * This includes changing the focus as views are removed or hidden, or as new
470 * views become available. Views indicate their willingness to take focus
471 * through the {@link #isFocusable} method. To change whether a view can take
472 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
473 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
474 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
475 * </p>
476 * <p>
477 * Focus movement is based on an algorithm which finds the nearest neighbor in a
478 * given direction. In rare cases, the default algorithm may not match the
479 * intended behavior of the developer. In these situations, you can provide
480 * explicit overrides by using these XML attributes in the layout file:
481 * <pre>
482 * nextFocusDown
483 * nextFocusLeft
484 * nextFocusRight
485 * nextFocusUp
486 * </pre>
487 * </p>
488 *
489 *
490 * <p>
491 * To get a particular view to take focus, call {@link #requestFocus()}.
492 * </p>
493 *
494 * <a name="TouchMode"></a>
495 * <h3>Touch Mode</h3>
496 * <p>
497 * When a user is navigating a user interface via directional keys such as a D-pad, it is
498 * necessary to give focus to actionable items such as buttons so the user can see
499 * what will take input.  If the device has touch capabilities, however, and the user
500 * begins interacting with the interface by touching it, it is no longer necessary to
501 * always highlight, or give focus to, a particular view.  This motivates a mode
502 * for interaction named 'touch mode'.
503 * </p>
504 * <p>
505 * For a touch capable device, once the user touches the screen, the device
506 * will enter touch mode.  From this point onward, only views for which
507 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
508 * Other views that are touchable, like buttons, will not take focus when touched; they will
509 * only fire the on click listeners.
510 * </p>
511 * <p>
512 * Any time a user hits a directional key, such as a D-pad direction, the view device will
513 * exit touch mode, and find a view to take focus, so that the user may resume interacting
514 * with the user interface without touching the screen again.
515 * </p>
516 * <p>
517 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
518 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
519 * </p>
520 *
521 * <a name="Scrolling"></a>
522 * <h3>Scrolling</h3>
523 * <p>
524 * The framework provides basic support for views that wish to internally
525 * scroll their content. This includes keeping track of the X and Y scroll
526 * offset as well as mechanisms for drawing scrollbars. See
527 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
528 * {@link #awakenScrollBars()} for more details.
529 * </p>
530 *
531 * <a name="Tags"></a>
532 * <h3>Tags</h3>
533 * <p>
534 * Unlike IDs, tags are not used to identify views. Tags are essentially an
535 * extra piece of information that can be associated with a view. They are most
536 * often used as a convenience to store data related to views in the views
537 * themselves rather than by putting them in a separate structure.
538 * </p>
539 *
540 * <a name="Properties"></a>
541 * <h3>Properties</h3>
542 * <p>
543 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
544 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
545 * available both in the {@link Property} form as well as in similarly-named setter/getter
546 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
547 * be used to set persistent state associated with these rendering-related properties on the view.
548 * The properties and methods can also be used in conjunction with
549 * {@link android.animation.Animator Animator}-based animations, described more in the
550 * <a href="#Animation">Animation</a> section.
551 * </p>
552 *
553 * <a name="Animation"></a>
554 * <h3>Animation</h3>
555 * <p>
556 * Starting with Android 3.0, the preferred way of animating views is to use the
557 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
558 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
559 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
560 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
561 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
562 * makes animating these View properties particularly easy and efficient.
563 * </p>
564 * <p>
565 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
566 * You can attach an {@link Animation} object to a view using
567 * {@link #setAnimation(Animation)} or
568 * {@link #startAnimation(Animation)}. The animation can alter the scale,
569 * rotation, translation and alpha of a view over time. If the animation is
570 * attached to a view that has children, the animation will affect the entire
571 * subtree rooted by that node. When an animation is started, the framework will
572 * take care of redrawing the appropriate views until the animation completes.
573 * </p>
574 *
575 * <a name="Security"></a>
576 * <h3>Security</h3>
577 * <p>
578 * Sometimes it is essential that an application be able to verify that an action
579 * is being performed with the full knowledge and consent of the user, such as
580 * granting a permission request, making a purchase or clicking on an advertisement.
581 * Unfortunately, a malicious application could try to spoof the user into
582 * performing these actions, unaware, by concealing the intended purpose of the view.
583 * As a remedy, the framework offers a touch filtering mechanism that can be used to
584 * improve the security of views that provide access to sensitive functionality.
585 * </p><p>
586 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
587 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
588 * will discard touches that are received whenever the view's window is obscured by
589 * another visible window.  As a result, the view will not receive touches whenever a
590 * toast, dialog or other window appears above the view's window.
591 * </p><p>
592 * For more fine-grained control over security, consider overriding the
593 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
594 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
595 * </p>
596 *
597 * @attr ref android.R.styleable#View_alpha
598 * @attr ref android.R.styleable#View_background
599 * @attr ref android.R.styleable#View_clickable
600 * @attr ref android.R.styleable#View_contentDescription
601 * @attr ref android.R.styleable#View_drawingCacheQuality
602 * @attr ref android.R.styleable#View_duplicateParentState
603 * @attr ref android.R.styleable#View_id
604 * @attr ref android.R.styleable#View_requiresFadingEdge
605 * @attr ref android.R.styleable#View_fadeScrollbars
606 * @attr ref android.R.styleable#View_fadingEdgeLength
607 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
608 * @attr ref android.R.styleable#View_fitsSystemWindows
609 * @attr ref android.R.styleable#View_isScrollContainer
610 * @attr ref android.R.styleable#View_focusable
611 * @attr ref android.R.styleable#View_focusableInTouchMode
612 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
613 * @attr ref android.R.styleable#View_keepScreenOn
614 * @attr ref android.R.styleable#View_layerType
615 * @attr ref android.R.styleable#View_longClickable
616 * @attr ref android.R.styleable#View_minHeight
617 * @attr ref android.R.styleable#View_minWidth
618 * @attr ref android.R.styleable#View_nextFocusDown
619 * @attr ref android.R.styleable#View_nextFocusLeft
620 * @attr ref android.R.styleable#View_nextFocusRight
621 * @attr ref android.R.styleable#View_nextFocusUp
622 * @attr ref android.R.styleable#View_onClick
623 * @attr ref android.R.styleable#View_padding
624 * @attr ref android.R.styleable#View_paddingBottom
625 * @attr ref android.R.styleable#View_paddingLeft
626 * @attr ref android.R.styleable#View_paddingRight
627 * @attr ref android.R.styleable#View_paddingTop
628 * @attr ref android.R.styleable#View_paddingStart
629 * @attr ref android.R.styleable#View_paddingEnd
630 * @attr ref android.R.styleable#View_saveEnabled
631 * @attr ref android.R.styleable#View_rotation
632 * @attr ref android.R.styleable#View_rotationX
633 * @attr ref android.R.styleable#View_rotationY
634 * @attr ref android.R.styleable#View_scaleX
635 * @attr ref android.R.styleable#View_scaleY
636 * @attr ref android.R.styleable#View_scrollX
637 * @attr ref android.R.styleable#View_scrollY
638 * @attr ref android.R.styleable#View_scrollbarSize
639 * @attr ref android.R.styleable#View_scrollbarStyle
640 * @attr ref android.R.styleable#View_scrollbars
641 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
642 * @attr ref android.R.styleable#View_scrollbarFadeDuration
643 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
644 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
645 * @attr ref android.R.styleable#View_scrollbarThumbVertical
646 * @attr ref android.R.styleable#View_scrollbarTrackVertical
647 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
648 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
649 * @attr ref android.R.styleable#View_soundEffectsEnabled
650 * @attr ref android.R.styleable#View_tag
651 * @attr ref android.R.styleable#View_textAlignment
652 * @attr ref android.R.styleable#View_transformPivotX
653 * @attr ref android.R.styleable#View_transformPivotY
654 * @attr ref android.R.styleable#View_translationX
655 * @attr ref android.R.styleable#View_translationY
656 * @attr ref android.R.styleable#View_visibility
657 *
658 * @see android.view.ViewGroup
659 */
660public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
661        AccessibilityEventSource {
662    private static final boolean DBG = false;
663
664    /**
665     * The logging tag used by this class with android.util.Log.
666     */
667    protected static final String VIEW_LOG_TAG = "View";
668
669    /**
670     * When set to true, apps will draw debugging information about their layouts.
671     *
672     * @hide
673     */
674    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
675
676    /**
677     * Used to mark a View that has no ID.
678     */
679    public static final int NO_ID = -1;
680
681    /**
682     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
683     * calling setFlags.
684     */
685    private static final int NOT_FOCUSABLE = 0x00000000;
686
687    /**
688     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
689     * setFlags.
690     */
691    private static final int FOCUSABLE = 0x00000001;
692
693    /**
694     * Mask for use with setFlags indicating bits used for focus.
695     */
696    private static final int FOCUSABLE_MASK = 0x00000001;
697
698    /**
699     * This view will adjust its padding to fit sytem windows (e.g. status bar)
700     */
701    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
702
703    /**
704     * This view is visible.
705     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
706     * android:visibility}.
707     */
708    public static final int VISIBLE = 0x00000000;
709
710    /**
711     * This view is invisible, but it still takes up space for layout purposes.
712     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
713     * android:visibility}.
714     */
715    public static final int INVISIBLE = 0x00000004;
716
717    /**
718     * This view is invisible, and it doesn't take any space for layout
719     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
720     * android:visibility}.
721     */
722    public static final int GONE = 0x00000008;
723
724    /**
725     * Mask for use with setFlags indicating bits used for visibility.
726     * {@hide}
727     */
728    static final int VISIBILITY_MASK = 0x0000000C;
729
730    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
731
732    /**
733     * This view is enabled. Interpretation varies by subclass.
734     * Use with ENABLED_MASK when calling setFlags.
735     * {@hide}
736     */
737    static final int ENABLED = 0x00000000;
738
739    /**
740     * This view is disabled. Interpretation varies by subclass.
741     * Use with ENABLED_MASK when calling setFlags.
742     * {@hide}
743     */
744    static final int DISABLED = 0x00000020;
745
746   /**
747    * Mask for use with setFlags indicating bits used for indicating whether
748    * this view is enabled
749    * {@hide}
750    */
751    static final int ENABLED_MASK = 0x00000020;
752
753    /**
754     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
755     * called and further optimizations will be performed. It is okay to have
756     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
757     * {@hide}
758     */
759    static final int WILL_NOT_DRAW = 0x00000080;
760
761    /**
762     * Mask for use with setFlags indicating bits used for indicating whether
763     * this view is will draw
764     * {@hide}
765     */
766    static final int DRAW_MASK = 0x00000080;
767
768    /**
769     * <p>This view doesn't show scrollbars.</p>
770     * {@hide}
771     */
772    static final int SCROLLBARS_NONE = 0x00000000;
773
774    /**
775     * <p>This view shows horizontal scrollbars.</p>
776     * {@hide}
777     */
778    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
779
780    /**
781     * <p>This view shows vertical scrollbars.</p>
782     * {@hide}
783     */
784    static final int SCROLLBARS_VERTICAL = 0x00000200;
785
786    /**
787     * <p>Mask for use with setFlags indicating bits used for indicating which
788     * scrollbars are enabled.</p>
789     * {@hide}
790     */
791    static final int SCROLLBARS_MASK = 0x00000300;
792
793    /**
794     * Indicates that the view should filter touches when its window is obscured.
795     * Refer to the class comments for more information about this security feature.
796     * {@hide}
797     */
798    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
799
800    /**
801     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
802     * that they are optional and should be skipped if the window has
803     * requested system UI flags that ignore those insets for layout.
804     */
805    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
806
807    /**
808     * <p>This view doesn't show fading edges.</p>
809     * {@hide}
810     */
811    static final int FADING_EDGE_NONE = 0x00000000;
812
813    /**
814     * <p>This view shows horizontal fading edges.</p>
815     * {@hide}
816     */
817    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
818
819    /**
820     * <p>This view shows vertical fading edges.</p>
821     * {@hide}
822     */
823    static final int FADING_EDGE_VERTICAL = 0x00002000;
824
825    /**
826     * <p>Mask for use with setFlags indicating bits used for indicating which
827     * fading edges are enabled.</p>
828     * {@hide}
829     */
830    static final int FADING_EDGE_MASK = 0x00003000;
831
832    /**
833     * <p>Indicates this view can be clicked. When clickable, a View reacts
834     * to clicks by notifying the OnClickListener.<p>
835     * {@hide}
836     */
837    static final int CLICKABLE = 0x00004000;
838
839    /**
840     * <p>Indicates this view is caching its drawing into a bitmap.</p>
841     * {@hide}
842     */
843    static final int DRAWING_CACHE_ENABLED = 0x00008000;
844
845    /**
846     * <p>Indicates that no icicle should be saved for this view.<p>
847     * {@hide}
848     */
849    static final int SAVE_DISABLED = 0x000010000;
850
851    /**
852     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
853     * property.</p>
854     * {@hide}
855     */
856    static final int SAVE_DISABLED_MASK = 0x000010000;
857
858    /**
859     * <p>Indicates that no drawing cache should ever be created for this view.<p>
860     * {@hide}
861     */
862    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
863
864    /**
865     * <p>Indicates this view can take / keep focus when int touch mode.</p>
866     * {@hide}
867     */
868    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
869
870    /**
871     * <p>Enables low quality mode for the drawing cache.</p>
872     */
873    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
874
875    /**
876     * <p>Enables high quality mode for the drawing cache.</p>
877     */
878    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
879
880    /**
881     * <p>Enables automatic quality mode for the drawing cache.</p>
882     */
883    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
884
885    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
886            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
887    };
888
889    /**
890     * <p>Mask for use with setFlags indicating bits used for the cache
891     * quality property.</p>
892     * {@hide}
893     */
894    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
895
896    /**
897     * <p>
898     * Indicates this view can be long clicked. When long clickable, a View
899     * reacts to long clicks by notifying the OnLongClickListener or showing a
900     * context menu.
901     * </p>
902     * {@hide}
903     */
904    static final int LONG_CLICKABLE = 0x00200000;
905
906    /**
907     * <p>Indicates that this view gets its drawable states from its direct parent
908     * and ignores its original internal states.</p>
909     *
910     * @hide
911     */
912    static final int DUPLICATE_PARENT_STATE = 0x00400000;
913
914    /**
915     * The scrollbar style to display the scrollbars inside the content area,
916     * without increasing the padding. The scrollbars will be overlaid with
917     * translucency on the view's content.
918     */
919    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
920
921    /**
922     * The scrollbar style to display the scrollbars inside the padded area,
923     * increasing the padding of the view. The scrollbars will not overlap the
924     * content area of the view.
925     */
926    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
927
928    /**
929     * The scrollbar style to display the scrollbars at the edge of the view,
930     * without increasing the padding. The scrollbars will be overlaid with
931     * translucency.
932     */
933    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
934
935    /**
936     * The scrollbar style to display the scrollbars at the edge of the view,
937     * increasing the padding of the view. The scrollbars will only overlap the
938     * background, if any.
939     */
940    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
941
942    /**
943     * Mask to check if the scrollbar style is overlay or inset.
944     * {@hide}
945     */
946    static final int SCROLLBARS_INSET_MASK = 0x01000000;
947
948    /**
949     * Mask to check if the scrollbar style is inside or outside.
950     * {@hide}
951     */
952    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
953
954    /**
955     * Mask for scrollbar style.
956     * {@hide}
957     */
958    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
959
960    /**
961     * View flag indicating that the screen should remain on while the
962     * window containing this view is visible to the user.  This effectively
963     * takes care of automatically setting the WindowManager's
964     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
965     */
966    public static final int KEEP_SCREEN_ON = 0x04000000;
967
968    /**
969     * View flag indicating whether this view should have sound effects enabled
970     * for events such as clicking and touching.
971     */
972    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
973
974    /**
975     * View flag indicating whether this view should have haptic feedback
976     * enabled for events such as long presses.
977     */
978    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
979
980    /**
981     * <p>Indicates that the view hierarchy should stop saving state when
982     * it reaches this view.  If state saving is initiated immediately at
983     * the view, it will be allowed.
984     * {@hide}
985     */
986    static final int PARENT_SAVE_DISABLED = 0x20000000;
987
988    /**
989     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
990     * {@hide}
991     */
992    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
993
994    /**
995     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
996     * should add all focusable Views regardless if they are focusable in touch mode.
997     */
998    public static final int FOCUSABLES_ALL = 0x00000000;
999
1000    /**
1001     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1002     * should add only Views focusable in touch mode.
1003     */
1004    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1005
1006    /**
1007     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1008     * should add only accessibility focusable Views.
1009     *
1010     * @hide
1011     */
1012    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
1013
1014    /**
1015     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1016     * item.
1017     */
1018    public static final int FOCUS_BACKWARD = 0x00000001;
1019
1020    /**
1021     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1022     * item.
1023     */
1024    public static final int FOCUS_FORWARD = 0x00000002;
1025
1026    /**
1027     * Use with {@link #focusSearch(int)}. Move focus to the left.
1028     */
1029    public static final int FOCUS_LEFT = 0x00000011;
1030
1031    /**
1032     * Use with {@link #focusSearch(int)}. Move focus up.
1033     */
1034    public static final int FOCUS_UP = 0x00000021;
1035
1036    /**
1037     * Use with {@link #focusSearch(int)}. Move focus to the right.
1038     */
1039    public static final int FOCUS_RIGHT = 0x00000042;
1040
1041    /**
1042     * Use with {@link #focusSearch(int)}. Move focus down.
1043     */
1044    public static final int FOCUS_DOWN = 0x00000082;
1045
1046    // Accessibility focus directions.
1047
1048    /**
1049     * The accessibility focus which is the current user position when
1050     * interacting with the accessibility framework.
1051     */
1052    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1053
1054    /**
1055     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1056     */
1057    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1058
1059    /**
1060     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1061     */
1062    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1063
1064    /**
1065     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1066     */
1067    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1068
1069    /**
1070     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1071     */
1072    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1073
1074    /**
1075     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1076     */
1077    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1078
1079    /**
1080     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1081     */
1082    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1083
1084    /**
1085     * Bits of {@link #getMeasuredWidthAndState()} and
1086     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1087     */
1088    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1089
1090    /**
1091     * Bits of {@link #getMeasuredWidthAndState()} and
1092     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1093     */
1094    public static final int MEASURED_STATE_MASK = 0xff000000;
1095
1096    /**
1097     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1098     * for functions that combine both width and height into a single int,
1099     * such as {@link #getMeasuredState()} and the childState argument of
1100     * {@link #resolveSizeAndState(int, int, int)}.
1101     */
1102    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1103
1104    /**
1105     * Bit of {@link #getMeasuredWidthAndState()} and
1106     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1107     * is smaller that the space the view would like to have.
1108     */
1109    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1110
1111    /**
1112     * Base View state sets
1113     */
1114    // Singles
1115    /**
1116     * Indicates the view has no states set. 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[] EMPTY_STATE_SET;
1124    /**
1125     * Indicates the view is enabled. 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[] ENABLED_STATE_SET;
1133    /**
1134     * Indicates the view is focused. 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     */
1141    protected static final int[] FOCUSED_STATE_SET;
1142    /**
1143     * Indicates the view is selected. States are used with
1144     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1145     * view depending on its state.
1146     *
1147     * @see android.graphics.drawable.Drawable
1148     * @see #getDrawableState()
1149     */
1150    protected static final int[] SELECTED_STATE_SET;
1151    /**
1152     * Indicates the view is pressed. States are used with
1153     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1154     * view depending on its state.
1155     *
1156     * @see android.graphics.drawable.Drawable
1157     * @see #getDrawableState()
1158     * @hide
1159     */
1160    protected static final int[] PRESSED_STATE_SET;
1161    /**
1162     * Indicates the view's window has focus. States are used with
1163     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1164     * view depending on its state.
1165     *
1166     * @see android.graphics.drawable.Drawable
1167     * @see #getDrawableState()
1168     */
1169    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1170    // Doubles
1171    /**
1172     * Indicates the view is enabled and has the focus.
1173     *
1174     * @see #ENABLED_STATE_SET
1175     * @see #FOCUSED_STATE_SET
1176     */
1177    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1178    /**
1179     * Indicates the view is enabled and selected.
1180     *
1181     * @see #ENABLED_STATE_SET
1182     * @see #SELECTED_STATE_SET
1183     */
1184    protected static final int[] ENABLED_SELECTED_STATE_SET;
1185    /**
1186     * Indicates the view is enabled and that its window has focus.
1187     *
1188     * @see #ENABLED_STATE_SET
1189     * @see #WINDOW_FOCUSED_STATE_SET
1190     */
1191    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1192    /**
1193     * Indicates the view is focused and selected.
1194     *
1195     * @see #FOCUSED_STATE_SET
1196     * @see #SELECTED_STATE_SET
1197     */
1198    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1199    /**
1200     * Indicates the view has the focus and that its window has the focus.
1201     *
1202     * @see #FOCUSED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is selected and that its window has the focus.
1208     *
1209     * @see #SELECTED_STATE_SET
1210     * @see #WINDOW_FOCUSED_STATE_SET
1211     */
1212    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1213    // Triples
1214    /**
1215     * Indicates the view is enabled, focused and selected.
1216     *
1217     * @see #ENABLED_STATE_SET
1218     * @see #FOCUSED_STATE_SET
1219     * @see #SELECTED_STATE_SET
1220     */
1221    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1222    /**
1223     * Indicates the view is enabled, focused and its window has the focus.
1224     *
1225     * @see #ENABLED_STATE_SET
1226     * @see #FOCUSED_STATE_SET
1227     * @see #WINDOW_FOCUSED_STATE_SET
1228     */
1229    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is enabled, selected and its window has the focus.
1232     *
1233     * @see #ENABLED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     * @see #WINDOW_FOCUSED_STATE_SET
1236     */
1237    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1238    /**
1239     * Indicates the view is focused, selected and its window has the focus.
1240     *
1241     * @see #FOCUSED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is enabled, focused, selected and its window
1248     * has the focus.
1249     *
1250     * @see #ENABLED_STATE_SET
1251     * @see #FOCUSED_STATE_SET
1252     * @see #SELECTED_STATE_SET
1253     * @see #WINDOW_FOCUSED_STATE_SET
1254     */
1255    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1256    /**
1257     * Indicates the view is pressed and its window has the focus.
1258     *
1259     * @see #PRESSED_STATE_SET
1260     * @see #WINDOW_FOCUSED_STATE_SET
1261     */
1262    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1263    /**
1264     * Indicates the view is pressed and selected.
1265     *
1266     * @see #PRESSED_STATE_SET
1267     * @see #SELECTED_STATE_SET
1268     */
1269    protected static final int[] PRESSED_SELECTED_STATE_SET;
1270    /**
1271     * Indicates the view is pressed, selected and its window has the focus.
1272     *
1273     * @see #PRESSED_STATE_SET
1274     * @see #SELECTED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed and focused.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #FOCUSED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, focused and its window has the focus.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #FOCUSED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, focused and selected.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #SELECTED_STATE_SET
1298     * @see #FOCUSED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, focused, selected and its window has the focus.
1303     *
1304     * @see #PRESSED_STATE_SET
1305     * @see #FOCUSED_STATE_SET
1306     * @see #SELECTED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed and enabled.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #ENABLED_STATE_SET
1315     */
1316    protected static final int[] PRESSED_ENABLED_STATE_SET;
1317    /**
1318     * Indicates the view is pressed, enabled and its window has the focus.
1319     *
1320     * @see #PRESSED_STATE_SET
1321     * @see #ENABLED_STATE_SET
1322     * @see #WINDOW_FOCUSED_STATE_SET
1323     */
1324    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1325    /**
1326     * Indicates the view is pressed, enabled and selected.
1327     *
1328     * @see #PRESSED_STATE_SET
1329     * @see #ENABLED_STATE_SET
1330     * @see #SELECTED_STATE_SET
1331     */
1332    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1333    /**
1334     * Indicates the view is pressed, enabled, selected and its window has the
1335     * focus.
1336     *
1337     * @see #PRESSED_STATE_SET
1338     * @see #ENABLED_STATE_SET
1339     * @see #SELECTED_STATE_SET
1340     * @see #WINDOW_FOCUSED_STATE_SET
1341     */
1342    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1343    /**
1344     * Indicates the view is pressed, enabled and focused.
1345     *
1346     * @see #PRESSED_STATE_SET
1347     * @see #ENABLED_STATE_SET
1348     * @see #FOCUSED_STATE_SET
1349     */
1350    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1351    /**
1352     * Indicates the view is pressed, enabled, focused and its window has the
1353     * focus.
1354     *
1355     * @see #PRESSED_STATE_SET
1356     * @see #ENABLED_STATE_SET
1357     * @see #FOCUSED_STATE_SET
1358     * @see #WINDOW_FOCUSED_STATE_SET
1359     */
1360    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1361    /**
1362     * Indicates the view is pressed, enabled, focused and selected.
1363     *
1364     * @see #PRESSED_STATE_SET
1365     * @see #ENABLED_STATE_SET
1366     * @see #SELECTED_STATE_SET
1367     * @see #FOCUSED_STATE_SET
1368     */
1369    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1370    /**
1371     * Indicates the view is pressed, enabled, focused, selected and its window
1372     * has the focus.
1373     *
1374     * @see #PRESSED_STATE_SET
1375     * @see #ENABLED_STATE_SET
1376     * @see #SELECTED_STATE_SET
1377     * @see #FOCUSED_STATE_SET
1378     * @see #WINDOW_FOCUSED_STATE_SET
1379     */
1380    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1381
1382    /**
1383     * The order here is very important to {@link #getDrawableState()}
1384     */
1385    private static final int[][] VIEW_STATE_SETS;
1386
1387    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1388    static final int VIEW_STATE_SELECTED = 1 << 1;
1389    static final int VIEW_STATE_FOCUSED = 1 << 2;
1390    static final int VIEW_STATE_ENABLED = 1 << 3;
1391    static final int VIEW_STATE_PRESSED = 1 << 4;
1392    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1393    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1394    static final int VIEW_STATE_HOVERED = 1 << 7;
1395    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1396    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1397
1398    static final int[] VIEW_STATE_IDS = new int[] {
1399        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1400        R.attr.state_selected,          VIEW_STATE_SELECTED,
1401        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1402        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1403        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1404        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1405        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1406        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1407        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1408        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1409    };
1410
1411    static {
1412        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1413            throw new IllegalStateException(
1414                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1415        }
1416        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1417        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1418            int viewState = R.styleable.ViewDrawableStates[i];
1419            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1420                if (VIEW_STATE_IDS[j] == viewState) {
1421                    orderedIds[i * 2] = viewState;
1422                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1423                }
1424            }
1425        }
1426        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1427        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1428        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1429            int numBits = Integer.bitCount(i);
1430            int[] set = new int[numBits];
1431            int pos = 0;
1432            for (int j = 0; j < orderedIds.length; j += 2) {
1433                if ((i & orderedIds[j+1]) != 0) {
1434                    set[pos++] = orderedIds[j];
1435                }
1436            }
1437            VIEW_STATE_SETS[i] = set;
1438        }
1439
1440        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1441        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1442        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1443        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1445        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1446        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1448        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1450        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1452                | VIEW_STATE_FOCUSED];
1453        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1454        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1456        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1457                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1458        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1459                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1460                | VIEW_STATE_ENABLED];
1461        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1463        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1465                | VIEW_STATE_ENABLED];
1466        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1468                | VIEW_STATE_ENABLED];
1469        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1471                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1472
1473        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1474        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1476        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1477                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1478        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1479                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1480                | VIEW_STATE_PRESSED];
1481        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1482                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1483        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1484                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1485                | VIEW_STATE_PRESSED];
1486        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1487                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1488                | VIEW_STATE_PRESSED];
1489        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1490                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1491                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1492        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1493                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1494        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1495                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1496                | VIEW_STATE_PRESSED];
1497        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1498                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1499                | VIEW_STATE_PRESSED];
1500        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1501                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1502                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1503        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1504                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1505                | VIEW_STATE_PRESSED];
1506        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1507                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1508                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1509        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1510                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1511                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1512        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1513                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1514                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1515                | VIEW_STATE_PRESSED];
1516    }
1517
1518    /**
1519     * Accessibility event types that are dispatched for text population.
1520     */
1521    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1522            AccessibilityEvent.TYPE_VIEW_CLICKED
1523            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1524            | AccessibilityEvent.TYPE_VIEW_SELECTED
1525            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1526            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1527            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1528            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1529            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1530            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1531            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED;
1532
1533    /**
1534     * Temporary Rect currently for use in setBackground().  This will probably
1535     * be extended in the future to hold our own class with more than just
1536     * a Rect. :)
1537     */
1538    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1539
1540    /**
1541     * Map used to store views' tags.
1542     */
1543    private SparseArray<Object> mKeyedTags;
1544
1545    /**
1546     * The next available accessiiblity id.
1547     */
1548    private static int sNextAccessibilityViewId;
1549
1550    /**
1551     * The animation currently associated with this view.
1552     * @hide
1553     */
1554    protected Animation mCurrentAnimation = null;
1555
1556    /**
1557     * Width as measured during measure pass.
1558     * {@hide}
1559     */
1560    @ViewDebug.ExportedProperty(category = "measurement")
1561    int mMeasuredWidth;
1562
1563    /**
1564     * Height as measured during measure pass.
1565     * {@hide}
1566     */
1567    @ViewDebug.ExportedProperty(category = "measurement")
1568    int mMeasuredHeight;
1569
1570    /**
1571     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1572     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1573     * its display list. This flag, used only when hw accelerated, allows us to clear the
1574     * flag while retaining this information until it's needed (at getDisplayList() time and
1575     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1576     *
1577     * {@hide}
1578     */
1579    boolean mRecreateDisplayList = false;
1580
1581    /**
1582     * The view's identifier.
1583     * {@hide}
1584     *
1585     * @see #setId(int)
1586     * @see #getId()
1587     */
1588    @ViewDebug.ExportedProperty(resolveId = true)
1589    int mID = NO_ID;
1590
1591    /**
1592     * The stable ID of this view for accessibility purposes.
1593     */
1594    int mAccessibilityViewId = NO_ID;
1595
1596    /**
1597     * The view's tag.
1598     * {@hide}
1599     *
1600     * @see #setTag(Object)
1601     * @see #getTag()
1602     */
1603    protected Object mTag;
1604
1605    // for mPrivateFlags:
1606    /** {@hide} */
1607    static final int WANTS_FOCUS                    = 0x00000001;
1608    /** {@hide} */
1609    static final int FOCUSED                        = 0x00000002;
1610    /** {@hide} */
1611    static final int SELECTED                       = 0x00000004;
1612    /** {@hide} */
1613    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1614    /** {@hide} */
1615    static final int HAS_BOUNDS                     = 0x00000010;
1616    /** {@hide} */
1617    static final int DRAWN                          = 0x00000020;
1618    /**
1619     * When this flag is set, this view is running an animation on behalf of its
1620     * children and should therefore not cancel invalidate requests, even if they
1621     * lie outside of this view's bounds.
1622     *
1623     * {@hide}
1624     */
1625    static final int DRAW_ANIMATION                 = 0x00000040;
1626    /** {@hide} */
1627    static final int SKIP_DRAW                      = 0x00000080;
1628    /** {@hide} */
1629    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1630    /** {@hide} */
1631    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1632    /** {@hide} */
1633    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1634    /** {@hide} */
1635    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1636    /** {@hide} */
1637    static final int FORCE_LAYOUT                   = 0x00001000;
1638    /** {@hide} */
1639    static final int LAYOUT_REQUIRED                = 0x00002000;
1640
1641    private static final int PRESSED                = 0x00004000;
1642
1643    /** {@hide} */
1644    static final int DRAWING_CACHE_VALID            = 0x00008000;
1645    /**
1646     * Flag used to indicate that this view should be drawn once more (and only once
1647     * more) after its animation has completed.
1648     * {@hide}
1649     */
1650    static final int ANIMATION_STARTED              = 0x00010000;
1651
1652    private static final int SAVE_STATE_CALLED      = 0x00020000;
1653
1654    /**
1655     * Indicates that the View returned true when onSetAlpha() was called and that
1656     * the alpha must be restored.
1657     * {@hide}
1658     */
1659    static final int ALPHA_SET                      = 0x00040000;
1660
1661    /**
1662     * Set by {@link #setScrollContainer(boolean)}.
1663     */
1664    static final int SCROLL_CONTAINER               = 0x00080000;
1665
1666    /**
1667     * Set by {@link #setScrollContainer(boolean)}.
1668     */
1669    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1670
1671    /**
1672     * View flag indicating whether this view was invalidated (fully or partially.)
1673     *
1674     * @hide
1675     */
1676    static final int DIRTY                          = 0x00200000;
1677
1678    /**
1679     * View flag indicating whether this view was invalidated by an opaque
1680     * invalidate request.
1681     *
1682     * @hide
1683     */
1684    static final int DIRTY_OPAQUE                   = 0x00400000;
1685
1686    /**
1687     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1688     *
1689     * @hide
1690     */
1691    static final int DIRTY_MASK                     = 0x00600000;
1692
1693    /**
1694     * Indicates whether the background is opaque.
1695     *
1696     * @hide
1697     */
1698    static final int OPAQUE_BACKGROUND              = 0x00800000;
1699
1700    /**
1701     * Indicates whether the scrollbars are opaque.
1702     *
1703     * @hide
1704     */
1705    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1706
1707    /**
1708     * Indicates whether the view is opaque.
1709     *
1710     * @hide
1711     */
1712    static final int OPAQUE_MASK                    = 0x01800000;
1713
1714    /**
1715     * Indicates a prepressed state;
1716     * the short time between ACTION_DOWN and recognizing
1717     * a 'real' press. Prepressed is used to recognize quick taps
1718     * even when they are shorter than ViewConfiguration.getTapTimeout().
1719     *
1720     * @hide
1721     */
1722    private static final int PREPRESSED             = 0x02000000;
1723
1724    /**
1725     * Indicates whether the view is temporarily detached.
1726     *
1727     * @hide
1728     */
1729    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1730
1731    /**
1732     * Indicates that we should awaken scroll bars once attached
1733     *
1734     * @hide
1735     */
1736    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1737
1738    /**
1739     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1740     * @hide
1741     */
1742    private static final int HOVERED              = 0x10000000;
1743
1744    /**
1745     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1746     * for transform operations
1747     *
1748     * @hide
1749     */
1750    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1751
1752    /** {@hide} */
1753    static final int ACTIVATED                    = 0x40000000;
1754
1755    /**
1756     * Indicates that this view was specifically invalidated, not just dirtied because some
1757     * child view was invalidated. The flag is used to determine when we need to recreate
1758     * a view's display list (as opposed to just returning a reference to its existing
1759     * display list).
1760     *
1761     * @hide
1762     */
1763    static final int INVALIDATED                  = 0x80000000;
1764
1765    /* Masks for mPrivateFlags2 */
1766
1767    /**
1768     * Indicates that this view has reported that it can accept the current drag's content.
1769     * Cleared when the drag operation concludes.
1770     * @hide
1771     */
1772    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1773
1774    /**
1775     * Indicates that this view is currently directly under the drag location in a
1776     * drag-and-drop operation involving content that it can accept.  Cleared when
1777     * the drag exits the view, or when the drag operation concludes.
1778     * @hide
1779     */
1780    static final int DRAG_HOVERED                 = 0x00000002;
1781
1782    /**
1783     * Horizontal layout direction of this view is from Left to Right.
1784     * Use with {@link #setLayoutDirection}.
1785     */
1786    public static final int LAYOUT_DIRECTION_LTR = 0;
1787
1788    /**
1789     * Horizontal layout direction of this view is from Right to Left.
1790     * Use with {@link #setLayoutDirection}.
1791     */
1792    public static final int LAYOUT_DIRECTION_RTL = 1;
1793
1794    /**
1795     * Horizontal layout direction of this view is inherited from its parent.
1796     * Use with {@link #setLayoutDirection}.
1797     */
1798    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1799
1800    /**
1801     * Horizontal layout direction of this view is from deduced from the default language
1802     * script for the locale. Use with {@link #setLayoutDirection}.
1803     */
1804    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1805
1806    /**
1807     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1808     * @hide
1809     */
1810    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1811
1812    /**
1813     * Mask for use with private flags indicating bits used for horizontal layout direction.
1814     * @hide
1815     */
1816    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1817
1818    /**
1819     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1820     * right-to-left direction.
1821     * @hide
1822     */
1823    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1824
1825    /**
1826     * Indicates whether the view horizontal layout direction has been resolved.
1827     * @hide
1828     */
1829    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1830
1831    /**
1832     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1833     * @hide
1834     */
1835    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1836
1837    /*
1838     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1839     * flag value.
1840     * @hide
1841     */
1842    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1843            LAYOUT_DIRECTION_LTR,
1844            LAYOUT_DIRECTION_RTL,
1845            LAYOUT_DIRECTION_INHERIT,
1846            LAYOUT_DIRECTION_LOCALE
1847    };
1848
1849    /**
1850     * Default horizontal layout direction.
1851     * @hide
1852     */
1853    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1854
1855    /**
1856     * Indicates that the view is tracking some sort of transient state
1857     * that the app should not need to be aware of, but that the framework
1858     * should take special care to preserve.
1859     *
1860     * @hide
1861     */
1862    static final int HAS_TRANSIENT_STATE = 0x00000100;
1863
1864
1865    /**
1866     * Text direction is inherited thru {@link ViewGroup}
1867     */
1868    public static final int TEXT_DIRECTION_INHERIT = 0;
1869
1870    /**
1871     * Text direction is using "first strong algorithm". The first strong directional character
1872     * determines the paragraph direction. If there is no strong directional character, the
1873     * paragraph direction is the view's resolved layout direction.
1874     */
1875    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1876
1877    /**
1878     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1879     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1880     * If there are neither, the paragraph direction is the view's resolved layout direction.
1881     */
1882    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1883
1884    /**
1885     * Text direction is forced to LTR.
1886     */
1887    public static final int TEXT_DIRECTION_LTR = 3;
1888
1889    /**
1890     * Text direction is forced to RTL.
1891     */
1892    public static final int TEXT_DIRECTION_RTL = 4;
1893
1894    /**
1895     * Text direction is coming from the system Locale.
1896     */
1897    public static final int TEXT_DIRECTION_LOCALE = 5;
1898
1899    /**
1900     * Default text direction is inherited
1901     */
1902    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1903
1904    /**
1905     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1906     * @hide
1907     */
1908    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1909
1910    /**
1911     * Mask for use with private flags indicating bits used for text direction.
1912     * @hide
1913     */
1914    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1915
1916    /**
1917     * Array of text direction flags for mapping attribute "textDirection" to correct
1918     * flag value.
1919     * @hide
1920     */
1921    private static final int[] TEXT_DIRECTION_FLAGS = {
1922            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1923            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1924            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1925            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1926            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1927            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1928    };
1929
1930    /**
1931     * Indicates whether the view text direction has been resolved.
1932     * @hide
1933     */
1934    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1935
1936    /**
1937     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1938     * @hide
1939     */
1940    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1941
1942    /**
1943     * Mask for use with private flags indicating bits used for resolved text direction.
1944     * @hide
1945     */
1946    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1947
1948    /**
1949     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1950     * @hide
1951     */
1952    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1953            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1954
1955    /*
1956     * Default text alignment. The text alignment of this View is inherited from its parent.
1957     * Use with {@link #setTextAlignment(int)}
1958     */
1959    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1960
1961    /**
1962     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1963     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1964     *
1965     * Use with {@link #setTextAlignment(int)}
1966     */
1967    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1968
1969    /**
1970     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1971     *
1972     * Use with {@link #setTextAlignment(int)}
1973     */
1974    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1975
1976    /**
1977     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1978     *
1979     * Use with {@link #setTextAlignment(int)}
1980     */
1981    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1982
1983    /**
1984     * Center the paragraph, e.g. ALIGN_CENTER.
1985     *
1986     * Use with {@link #setTextAlignment(int)}
1987     */
1988    public static final int TEXT_ALIGNMENT_CENTER = 4;
1989
1990    /**
1991     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
1992     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
1993     *
1994     * Use with {@link #setTextAlignment(int)}
1995     */
1996    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
1997
1998    /**
1999     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2000     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2001     *
2002     * Use with {@link #setTextAlignment(int)}
2003     */
2004    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2005
2006    /**
2007     * Default text alignment is inherited
2008     */
2009    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2010
2011    /**
2012      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2013      * @hide
2014      */
2015    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2016
2017    /**
2018      * Mask for use with private flags indicating bits used for text alignment.
2019      * @hide
2020      */
2021    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2022
2023    /**
2024     * Array of text direction flags for mapping attribute "textAlignment" to correct
2025     * flag value.
2026     * @hide
2027     */
2028    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2029            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2030            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2031            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2032            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2033            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2034            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2035            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2036    };
2037
2038    /**
2039     * Indicates whether the view text alignment has been resolved.
2040     * @hide
2041     */
2042    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2043
2044    /**
2045     * Bit shift to get the resolved text alignment.
2046     * @hide
2047     */
2048    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2049
2050    /**
2051     * Mask for use with private flags indicating bits used for text alignment.
2052     * @hide
2053     */
2054    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2055
2056    /**
2057     * Indicates whether if the view text alignment has been resolved to gravity
2058     */
2059    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2060            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2061
2062    // Accessiblity constants for mPrivateFlags2
2063
2064    /**
2065     * Shift for accessibility related bits in {@link #mPrivateFlags2}.
2066     */
2067    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2068
2069    /**
2070     * Automatically determine whether a view is important for accessibility.
2071     */
2072    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2073
2074    /**
2075     * The view is important for accessibility.
2076     */
2077    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2078
2079    /**
2080     * The view is not important for accessibility.
2081     */
2082    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2083
2084    /**
2085     * The default whether the view is important for accessiblity.
2086     */
2087    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2088
2089    /**
2090     * Mask for obtainig the bits which specify how to determine
2091     * whether a view is important for accessibility.
2092     */
2093    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2094        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2095        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2096
2097    /**
2098     * Flag indicating whether a view has accessibility focus.
2099     */
2100    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2101
2102    /**
2103     * Flag indicating whether a view state for accessibility has changed.
2104     */
2105    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2106
2107    /* End of masks for mPrivateFlags2 */
2108
2109    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2110
2111    /**
2112     * Always allow a user to over-scroll this view, provided it is a
2113     * view that can scroll.
2114     *
2115     * @see #getOverScrollMode()
2116     * @see #setOverScrollMode(int)
2117     */
2118    public static final int OVER_SCROLL_ALWAYS = 0;
2119
2120    /**
2121     * Allow a user to over-scroll this view only if the content is large
2122     * enough to meaningfully scroll, provided it is a view that can scroll.
2123     *
2124     * @see #getOverScrollMode()
2125     * @see #setOverScrollMode(int)
2126     */
2127    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2128
2129    /**
2130     * Never allow a user to over-scroll this view.
2131     *
2132     * @see #getOverScrollMode()
2133     * @see #setOverScrollMode(int)
2134     */
2135    public static final int OVER_SCROLL_NEVER = 2;
2136
2137    /**
2138     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2139     * requested the system UI (status bar) to be visible (the default).
2140     *
2141     * @see #setSystemUiVisibility(int)
2142     */
2143    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2144
2145    /**
2146     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2147     * system UI to enter an unobtrusive "low profile" mode.
2148     *
2149     * <p>This is for use in games, book readers, video players, or any other
2150     * "immersive" application where the usual system chrome is deemed too distracting.
2151     *
2152     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2153     *
2154     * @see #setSystemUiVisibility(int)
2155     */
2156    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2157
2158    /**
2159     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2160     * system navigation be temporarily hidden.
2161     *
2162     * <p>This is an even less obtrusive state than that called for by
2163     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2164     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2165     * those to disappear. This is useful (in conjunction with the
2166     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2167     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2168     * window flags) for displaying content using every last pixel on the display.
2169     *
2170     * <p>There is a limitation: because navigation controls are so important, the least user
2171     * interaction will cause them to reappear immediately.  When this happens, both
2172     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2173     * so that both elements reappear at the same time.
2174     *
2175     * @see #setSystemUiVisibility(int)
2176     */
2177    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2178
2179    /**
2180     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2181     * into the normal fullscreen mode so that its content can take over the screen
2182     * while still allowing the user to interact with the application.
2183     *
2184     * <p>This has the same visual effect as
2185     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2186     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2187     * meaning that non-critical screen decorations (such as the status bar) will be
2188     * hidden while the user is in the View's window, focusing the experience on
2189     * that content.  Unlike the window flag, if you are using ActionBar in
2190     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2191     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2192     * hide the action bar.
2193     *
2194     * <p>This approach to going fullscreen is best used over the window flag when
2195     * it is a transient state -- that is, the application does this at certain
2196     * points in its user interaction where it wants to allow the user to focus
2197     * on content, but not as a continuous state.  For situations where the application
2198     * would like to simply stay full screen the entire time (such as a game that
2199     * wants to take over the screen), the
2200     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2201     * is usually a better approach.  The state set here will be removed by the system
2202     * in various situations (such as the user moving to another application) like
2203     * the other system UI states.
2204     *
2205     * <p>When using this flag, the application should provide some easy facility
2206     * for the user to go out of it.  A common example would be in an e-book
2207     * reader, where tapping on the screen brings back whatever screen and UI
2208     * decorations that had been hidden while the user was immersed in reading
2209     * the book.
2210     *
2211     * @see #setSystemUiVisibility(int)
2212     */
2213    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2214
2215    /**
2216     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2217     * flags, we would like a stable view of the content insets given to
2218     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2219     * will always represent the worst case that the application can expect
2220     * as a continue state.  In practice this means with any of system bar,
2221     * nav bar, and status bar shown, but not the space that would be needed
2222     * for an input method.
2223     *
2224     * <p>If you are using ActionBar in
2225     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2226     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2227     * insets it adds to those given to the application.
2228     */
2229    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2230
2231    /**
2232     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2233     * to be layed out as if it has requested
2234     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2235     * allows it to avoid artifacts when switching in and out of that mode, at
2236     * the expense that some of its user interface may be covered by screen
2237     * decorations when they are shown.  You can perform layout of your inner
2238     * UI elements to account for the navagation system UI through the
2239     * {@link #fitSystemWindows(Rect)} method.
2240     */
2241    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2242
2243    /**
2244     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2245     * to be layed out as if it has requested
2246     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2247     * allows it to avoid artifacts when switching in and out of that mode, at
2248     * the expense that some of its user interface may be covered by screen
2249     * decorations when they are shown.  You can perform layout of your inner
2250     * UI elements to account for non-fullscreen system UI through the
2251     * {@link #fitSystemWindows(Rect)} method.
2252     */
2253    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2254
2255    /**
2256     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2257     */
2258    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2259
2260    /**
2261     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2262     */
2263    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2264
2265    /**
2266     * @hide
2267     *
2268     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2269     * out of the public fields to keep the undefined bits out of the developer's way.
2270     *
2271     * Flag to make the status bar not expandable.  Unless you also
2272     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2273     */
2274    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
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 hide notification icons and scrolling ticker text.
2283     */
2284    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2285
2286    /**
2287     * @hide
2288     *
2289     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2290     * out of the public fields to keep the undefined bits out of the developer's way.
2291     *
2292     * Flag to disable incoming notification alerts.  This will not block
2293     * icons, but it will block sound, vibrating and other visual or aural notifications.
2294     */
2295    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2296
2297    /**
2298     * @hide
2299     *
2300     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2301     * out of the public fields to keep the undefined bits out of the developer's way.
2302     *
2303     * Flag to hide only the scrolling ticker.  Note that
2304     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2305     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2306     */
2307    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
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 the center system info area.
2316     */
2317    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2318
2319    /**
2320     * @hide
2321     *
2322     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2323     * out of the public fields to keep the undefined bits out of the developer's way.
2324     *
2325     * Flag to hide only the home button.  Don't use this
2326     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2327     */
2328    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2329
2330    /**
2331     * @hide
2332     *
2333     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2334     * out of the public fields to keep the undefined bits out of the developer's way.
2335     *
2336     * Flag to hide only the back button. Don't use this
2337     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2338     */
2339    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2340
2341    /**
2342     * @hide
2343     *
2344     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2345     * out of the public fields to keep the undefined bits out of the developer's way.
2346     *
2347     * Flag to hide only the clock.  You might use this if your activity has
2348     * its own clock making the status bar's clock redundant.
2349     */
2350    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2351
2352    /**
2353     * @hide
2354     *
2355     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2356     * out of the public fields to keep the undefined bits out of the developer's way.
2357     *
2358     * Flag to hide only the recent apps button. Don't use this
2359     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2360     */
2361    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2362
2363    /**
2364     * @hide
2365     */
2366    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2367
2368    /**
2369     * These are the system UI flags that can be cleared by events outside
2370     * of an application.  Currently this is just the ability to tap on the
2371     * screen while hiding the navigation bar to have it return.
2372     * @hide
2373     */
2374    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2375            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2376            | SYSTEM_UI_FLAG_FULLSCREEN;
2377
2378    /**
2379     * Flags that can impact the layout in relation to system UI.
2380     */
2381    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2382            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2383            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2384
2385    /**
2386     * Find views that render the specified text.
2387     *
2388     * @see #findViewsWithText(ArrayList, CharSequence, int)
2389     */
2390    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2391
2392    /**
2393     * Find find views that contain the specified content description.
2394     *
2395     * @see #findViewsWithText(ArrayList, CharSequence, int)
2396     */
2397    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2398
2399    /**
2400     * Find views that contain {@link AccessibilityNodeProvider}. Such
2401     * a View is a root of virtual view hierarchy and may contain the searched
2402     * text. If this flag is set Views with providers are automatically
2403     * added and it is a responsibility of the client to call the APIs of
2404     * the provider to determine whether the virtual tree rooted at this View
2405     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2406     * represeting the virtual views with this text.
2407     *
2408     * @see #findViewsWithText(ArrayList, CharSequence, int)
2409     *
2410     * @hide
2411     */
2412    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2413
2414    /**
2415     * Indicates that the screen has changed state and is now off.
2416     *
2417     * @see #onScreenStateChanged(int)
2418     */
2419    public static final int SCREEN_STATE_OFF = 0x0;
2420
2421    /**
2422     * Indicates that the screen has changed state and is now on.
2423     *
2424     * @see #onScreenStateChanged(int)
2425     */
2426    public static final int SCREEN_STATE_ON = 0x1;
2427
2428    /**
2429     * Controls the over-scroll mode for this view.
2430     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2431     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2432     * and {@link #OVER_SCROLL_NEVER}.
2433     */
2434    private int mOverScrollMode;
2435
2436    /**
2437     * The parent this view is attached to.
2438     * {@hide}
2439     *
2440     * @see #getParent()
2441     */
2442    protected ViewParent mParent;
2443
2444    /**
2445     * {@hide}
2446     */
2447    AttachInfo mAttachInfo;
2448
2449    /**
2450     * {@hide}
2451     */
2452    @ViewDebug.ExportedProperty(flagMapping = {
2453        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2454                name = "FORCE_LAYOUT"),
2455        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2456                name = "LAYOUT_REQUIRED"),
2457        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2458            name = "DRAWING_CACHE_INVALID", outputIf = false),
2459        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2460        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2461        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2462        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2463    })
2464    int mPrivateFlags;
2465    int mPrivateFlags2;
2466
2467    /**
2468     * This view's request for the visibility of the status bar.
2469     * @hide
2470     */
2471    @ViewDebug.ExportedProperty(flagMapping = {
2472        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2473                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2474                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2475        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2476                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2477                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2478        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2479                                equals = SYSTEM_UI_FLAG_VISIBLE,
2480                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2481    })
2482    int mSystemUiVisibility;
2483
2484    /**
2485     * Reference count for transient state.
2486     * @see #setHasTransientState(boolean)
2487     */
2488    int mTransientStateCount = 0;
2489
2490    /**
2491     * Count of how many windows this view has been attached to.
2492     */
2493    int mWindowAttachCount;
2494
2495    /**
2496     * The layout parameters associated with this view and used by the parent
2497     * {@link android.view.ViewGroup} to determine how this view should be
2498     * laid out.
2499     * {@hide}
2500     */
2501    protected ViewGroup.LayoutParams mLayoutParams;
2502
2503    /**
2504     * The view flags hold various views states.
2505     * {@hide}
2506     */
2507    @ViewDebug.ExportedProperty
2508    int mViewFlags;
2509
2510    static class TransformationInfo {
2511        /**
2512         * The transform matrix for the View. This transform is calculated internally
2513         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2514         * is used by default. Do *not* use this variable directly; instead call
2515         * getMatrix(), which will automatically recalculate the matrix if necessary
2516         * to get the correct matrix based on the latest rotation and scale properties.
2517         */
2518        private final Matrix mMatrix = new Matrix();
2519
2520        /**
2521         * The transform matrix for the View. This transform is calculated internally
2522         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2523         * is used by default. Do *not* use this variable directly; instead call
2524         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2525         * to get the correct matrix based on the latest rotation and scale properties.
2526         */
2527        private Matrix mInverseMatrix;
2528
2529        /**
2530         * An internal variable that tracks whether we need to recalculate the
2531         * transform matrix, based on whether the rotation or scaleX/Y properties
2532         * have changed since the matrix was last calculated.
2533         */
2534        boolean mMatrixDirty = false;
2535
2536        /**
2537         * An internal variable that tracks whether we need to recalculate the
2538         * transform matrix, based on whether the rotation or scaleX/Y properties
2539         * have changed since the matrix was last calculated.
2540         */
2541        private boolean mInverseMatrixDirty = true;
2542
2543        /**
2544         * A variable that tracks whether we need to recalculate the
2545         * transform matrix, based on whether the rotation or scaleX/Y properties
2546         * have changed since the matrix was last calculated. This variable
2547         * is only valid after a call to updateMatrix() or to a function that
2548         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2549         */
2550        private boolean mMatrixIsIdentity = true;
2551
2552        /**
2553         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2554         */
2555        private Camera mCamera = null;
2556
2557        /**
2558         * This matrix is used when computing the matrix for 3D rotations.
2559         */
2560        private Matrix matrix3D = null;
2561
2562        /**
2563         * These prev values are used to recalculate a centered pivot point when necessary. The
2564         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2565         * set), so thes values are only used then as well.
2566         */
2567        private int mPrevWidth = -1;
2568        private int mPrevHeight = -1;
2569
2570        /**
2571         * The degrees rotation around the vertical axis through the pivot point.
2572         */
2573        @ViewDebug.ExportedProperty
2574        float mRotationY = 0f;
2575
2576        /**
2577         * The degrees rotation around the horizontal axis through the pivot point.
2578         */
2579        @ViewDebug.ExportedProperty
2580        float mRotationX = 0f;
2581
2582        /**
2583         * The degrees rotation around the pivot point.
2584         */
2585        @ViewDebug.ExportedProperty
2586        float mRotation = 0f;
2587
2588        /**
2589         * The amount of translation of the object away from its left property (post-layout).
2590         */
2591        @ViewDebug.ExportedProperty
2592        float mTranslationX = 0f;
2593
2594        /**
2595         * The amount of translation of the object away from its top property (post-layout).
2596         */
2597        @ViewDebug.ExportedProperty
2598        float mTranslationY = 0f;
2599
2600        /**
2601         * The amount of scale in the x direction around the pivot point. A
2602         * value of 1 means no scaling is applied.
2603         */
2604        @ViewDebug.ExportedProperty
2605        float mScaleX = 1f;
2606
2607        /**
2608         * The amount of scale in the y direction around the pivot point. A
2609         * value of 1 means no scaling is applied.
2610         */
2611        @ViewDebug.ExportedProperty
2612        float mScaleY = 1f;
2613
2614        /**
2615         * The x location of the point around which the view is rotated and scaled.
2616         */
2617        @ViewDebug.ExportedProperty
2618        float mPivotX = 0f;
2619
2620        /**
2621         * The y location of the point around which the view is rotated and scaled.
2622         */
2623        @ViewDebug.ExportedProperty
2624        float mPivotY = 0f;
2625
2626        /**
2627         * The opacity of the View. This is a value from 0 to 1, where 0 means
2628         * completely transparent and 1 means completely opaque.
2629         */
2630        @ViewDebug.ExportedProperty
2631        float mAlpha = 1f;
2632    }
2633
2634    TransformationInfo mTransformationInfo;
2635
2636    private boolean mLastIsOpaque;
2637
2638    /**
2639     * Convenience value to check for float values that are close enough to zero to be considered
2640     * zero.
2641     */
2642    private static final float NONZERO_EPSILON = .001f;
2643
2644    /**
2645     * The distance in pixels from the left edge of this view's parent
2646     * to the left edge of this view.
2647     * {@hide}
2648     */
2649    @ViewDebug.ExportedProperty(category = "layout")
2650    protected int mLeft;
2651    /**
2652     * The distance in pixels from the left edge of this view's parent
2653     * to the right edge of this view.
2654     * {@hide}
2655     */
2656    @ViewDebug.ExportedProperty(category = "layout")
2657    protected int mRight;
2658    /**
2659     * The distance in pixels from the top edge of this view's parent
2660     * to the top edge of this view.
2661     * {@hide}
2662     */
2663    @ViewDebug.ExportedProperty(category = "layout")
2664    protected int mTop;
2665    /**
2666     * The distance in pixels from the top edge of this view's parent
2667     * to the bottom edge of this view.
2668     * {@hide}
2669     */
2670    @ViewDebug.ExportedProperty(category = "layout")
2671    protected int mBottom;
2672
2673    /**
2674     * The offset, in pixels, by which the content of this view is scrolled
2675     * horizontally.
2676     * {@hide}
2677     */
2678    @ViewDebug.ExportedProperty(category = "scrolling")
2679    protected int mScrollX;
2680    /**
2681     * The offset, in pixels, by which the content of this view is scrolled
2682     * vertically.
2683     * {@hide}
2684     */
2685    @ViewDebug.ExportedProperty(category = "scrolling")
2686    protected int mScrollY;
2687
2688    /**
2689     * The left padding in pixels, that is the distance in pixels between the
2690     * left edge of this view and the left edge of its content.
2691     * {@hide}
2692     */
2693    @ViewDebug.ExportedProperty(category = "padding")
2694    protected int mPaddingLeft;
2695    /**
2696     * The right padding in pixels, that is the distance in pixels between the
2697     * right edge of this view and the right edge of its content.
2698     * {@hide}
2699     */
2700    @ViewDebug.ExportedProperty(category = "padding")
2701    protected int mPaddingRight;
2702    /**
2703     * The top padding in pixels, that is the distance in pixels between the
2704     * top edge of this view and the top edge of its content.
2705     * {@hide}
2706     */
2707    @ViewDebug.ExportedProperty(category = "padding")
2708    protected int mPaddingTop;
2709    /**
2710     * The bottom padding in pixels, that is the distance in pixels between the
2711     * bottom edge of this view and the bottom edge of its content.
2712     * {@hide}
2713     */
2714    @ViewDebug.ExportedProperty(category = "padding")
2715    protected int mPaddingBottom;
2716
2717    /**
2718     * The layout insets in pixels, that is the distance in pixels between the
2719     * visible edges of this view its bounds.
2720     */
2721    private Insets mLayoutInsets;
2722
2723    /**
2724     * Briefly describes the view and is primarily used for accessibility support.
2725     */
2726    private CharSequence mContentDescription;
2727
2728    /**
2729     * Cache the paddingRight set by the user to append to the scrollbar's size.
2730     *
2731     * @hide
2732     */
2733    @ViewDebug.ExportedProperty(category = "padding")
2734    protected int mUserPaddingRight;
2735
2736    /**
2737     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2738     *
2739     * @hide
2740     */
2741    @ViewDebug.ExportedProperty(category = "padding")
2742    protected int mUserPaddingBottom;
2743
2744    /**
2745     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2746     *
2747     * @hide
2748     */
2749    @ViewDebug.ExportedProperty(category = "padding")
2750    protected int mUserPaddingLeft;
2751
2752    /**
2753     * Cache if the user padding is relative.
2754     *
2755     */
2756    @ViewDebug.ExportedProperty(category = "padding")
2757    boolean mUserPaddingRelative;
2758
2759    /**
2760     * Cache the paddingStart set by the user to append to the scrollbar's size.
2761     *
2762     */
2763    @ViewDebug.ExportedProperty(category = "padding")
2764    int mUserPaddingStart;
2765
2766    /**
2767     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2768     *
2769     */
2770    @ViewDebug.ExportedProperty(category = "padding")
2771    int mUserPaddingEnd;
2772
2773    /**
2774     * @hide
2775     */
2776    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2777    /**
2778     * @hide
2779     */
2780    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2781
2782    private Drawable mBackground;
2783
2784    private int mBackgroundResource;
2785    private boolean mBackgroundSizeChanged;
2786
2787    static class ListenerInfo {
2788        /**
2789         * Listener used to dispatch focus change events.
2790         * This field should be made private, so it is hidden from the SDK.
2791         * {@hide}
2792         */
2793        protected OnFocusChangeListener mOnFocusChangeListener;
2794
2795        /**
2796         * Listeners for layout change events.
2797         */
2798        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2799
2800        /**
2801         * Listeners for attach events.
2802         */
2803        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2804
2805        /**
2806         * Listener used to dispatch click events.
2807         * This field should be made private, so it is hidden from the SDK.
2808         * {@hide}
2809         */
2810        public OnClickListener mOnClickListener;
2811
2812        /**
2813         * Listener used to dispatch long click events.
2814         * This field should be made private, so it is hidden from the SDK.
2815         * {@hide}
2816         */
2817        protected OnLongClickListener mOnLongClickListener;
2818
2819        /**
2820         * Listener used to build the context menu.
2821         * This field should be made private, so it is hidden from the SDK.
2822         * {@hide}
2823         */
2824        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2825
2826        private OnKeyListener mOnKeyListener;
2827
2828        private OnTouchListener mOnTouchListener;
2829
2830        private OnHoverListener mOnHoverListener;
2831
2832        private OnGenericMotionListener mOnGenericMotionListener;
2833
2834        private OnDragListener mOnDragListener;
2835
2836        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2837    }
2838
2839    ListenerInfo mListenerInfo;
2840
2841    /**
2842     * The application environment this view lives in.
2843     * This field should be made private, so it is hidden from the SDK.
2844     * {@hide}
2845     */
2846    protected Context mContext;
2847
2848    private final Resources mResources;
2849
2850    private ScrollabilityCache mScrollCache;
2851
2852    private int[] mDrawableState = null;
2853
2854    /**
2855     * Set to true when drawing cache is enabled and cannot be created.
2856     *
2857     * @hide
2858     */
2859    public boolean mCachingFailed;
2860
2861    private Bitmap mDrawingCache;
2862    private Bitmap mUnscaledDrawingCache;
2863    private HardwareLayer mHardwareLayer;
2864    DisplayList mDisplayList;
2865
2866    /**
2867     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2868     * the user may specify which view to go to next.
2869     */
2870    private int mNextFocusLeftId = View.NO_ID;
2871
2872    /**
2873     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2874     * the user may specify which view to go to next.
2875     */
2876    private int mNextFocusRightId = View.NO_ID;
2877
2878    /**
2879     * When this view has focus and the next focus is {@link #FOCUS_UP},
2880     * the user may specify which view to go to next.
2881     */
2882    private int mNextFocusUpId = View.NO_ID;
2883
2884    /**
2885     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2886     * the user may specify which view to go to next.
2887     */
2888    private int mNextFocusDownId = View.NO_ID;
2889
2890    /**
2891     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2892     * the user may specify which view to go to next.
2893     */
2894    int mNextFocusForwardId = View.NO_ID;
2895
2896    private CheckForLongPress mPendingCheckForLongPress;
2897    private CheckForTap mPendingCheckForTap = null;
2898    private PerformClick mPerformClick;
2899    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2900
2901    private UnsetPressedState mUnsetPressedState;
2902
2903    /**
2904     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2905     * up event while a long press is invoked as soon as the long press duration is reached, so
2906     * a long press could be performed before the tap is checked, in which case the tap's action
2907     * should not be invoked.
2908     */
2909    private boolean mHasPerformedLongPress;
2910
2911    /**
2912     * The minimum height of the view. We'll try our best to have the height
2913     * of this view to at least this amount.
2914     */
2915    @ViewDebug.ExportedProperty(category = "measurement")
2916    private int mMinHeight;
2917
2918    /**
2919     * The minimum width of the view. We'll try our best to have the width
2920     * of this view to at least this amount.
2921     */
2922    @ViewDebug.ExportedProperty(category = "measurement")
2923    private int mMinWidth;
2924
2925    /**
2926     * The delegate to handle touch events that are physically in this view
2927     * but should be handled by another view.
2928     */
2929    private TouchDelegate mTouchDelegate = null;
2930
2931    /**
2932     * Solid color to use as a background when creating the drawing cache. Enables
2933     * the cache to use 16 bit bitmaps instead of 32 bit.
2934     */
2935    private int mDrawingCacheBackgroundColor = 0;
2936
2937    /**
2938     * Special tree observer used when mAttachInfo is null.
2939     */
2940    private ViewTreeObserver mFloatingTreeObserver;
2941
2942    /**
2943     * Cache the touch slop from the context that created the view.
2944     */
2945    private int mTouchSlop;
2946
2947    /**
2948     * Object that handles automatic animation of view properties.
2949     */
2950    private ViewPropertyAnimator mAnimator = null;
2951
2952    /**
2953     * Flag indicating that a drag can cross window boundaries.  When
2954     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2955     * with this flag set, all visible applications will be able to participate
2956     * in the drag operation and receive the dragged content.
2957     *
2958     * @hide
2959     */
2960    public static final int DRAG_FLAG_GLOBAL = 1;
2961
2962    /**
2963     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2964     */
2965    private float mVerticalScrollFactor;
2966
2967    /**
2968     * Position of the vertical scroll bar.
2969     */
2970    private int mVerticalScrollbarPosition;
2971
2972    /**
2973     * Position the scroll bar at the default position as determined by the system.
2974     */
2975    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2976
2977    /**
2978     * Position the scroll bar along the left edge.
2979     */
2980    public static final int SCROLLBAR_POSITION_LEFT = 1;
2981
2982    /**
2983     * Position the scroll bar along the right edge.
2984     */
2985    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2986
2987    /**
2988     * Indicates that the view does not have a layer.
2989     *
2990     * @see #getLayerType()
2991     * @see #setLayerType(int, android.graphics.Paint)
2992     * @see #LAYER_TYPE_SOFTWARE
2993     * @see #LAYER_TYPE_HARDWARE
2994     */
2995    public static final int LAYER_TYPE_NONE = 0;
2996
2997    /**
2998     * <p>Indicates that the view has a software layer. A software layer is backed
2999     * by a bitmap and causes the view to be rendered using Android's software
3000     * rendering pipeline, even if hardware acceleration is enabled.</p>
3001     *
3002     * <p>Software layers have various usages:</p>
3003     * <p>When the application is not using hardware acceleration, a software layer
3004     * is useful to apply a specific color filter and/or blending mode and/or
3005     * translucency to a view and all its children.</p>
3006     * <p>When the application is using hardware acceleration, a software layer
3007     * is useful to render drawing primitives not supported by the hardware
3008     * accelerated pipeline. It can also be used to cache a complex view tree
3009     * into a texture and reduce the complexity of drawing operations. For instance,
3010     * when animating a complex view tree with a translation, a software layer can
3011     * be used to render the view tree only once.</p>
3012     * <p>Software layers should be avoided when the affected view tree updates
3013     * often. Every update will require to re-render the software layer, which can
3014     * potentially be slow (particularly when hardware acceleration is turned on
3015     * since the layer will have to be uploaded into a hardware texture after every
3016     * update.)</p>
3017     *
3018     * @see #getLayerType()
3019     * @see #setLayerType(int, android.graphics.Paint)
3020     * @see #LAYER_TYPE_NONE
3021     * @see #LAYER_TYPE_HARDWARE
3022     */
3023    public static final int LAYER_TYPE_SOFTWARE = 1;
3024
3025    /**
3026     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3027     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3028     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3029     * rendering pipeline, but only if hardware acceleration is turned on for the
3030     * view hierarchy. When hardware acceleration is turned off, hardware layers
3031     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3032     *
3033     * <p>A hardware layer is useful to apply a specific color filter and/or
3034     * blending mode and/or translucency to a view and all its children.</p>
3035     * <p>A hardware layer can be used to cache a complex view tree into a
3036     * texture and reduce the complexity of drawing operations. For instance,
3037     * when animating a complex view tree with a translation, a hardware layer can
3038     * be used to render the view tree only once.</p>
3039     * <p>A hardware layer can also be used to increase the rendering quality when
3040     * rotation transformations are applied on a view. It can also be used to
3041     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3042     *
3043     * @see #getLayerType()
3044     * @see #setLayerType(int, android.graphics.Paint)
3045     * @see #LAYER_TYPE_NONE
3046     * @see #LAYER_TYPE_SOFTWARE
3047     */
3048    public static final int LAYER_TYPE_HARDWARE = 2;
3049
3050    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3051            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3052            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3053            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3054    })
3055    int mLayerType = LAYER_TYPE_NONE;
3056    Paint mLayerPaint;
3057    Rect mLocalDirtyRect;
3058
3059    /**
3060     * Set to true when the view is sending hover accessibility events because it
3061     * is the innermost hovered view.
3062     */
3063    private boolean mSendingHoverAccessibilityEvents;
3064
3065    /**
3066     * Simple constructor to use when creating a view from code.
3067     *
3068     * @param context The Context the view is running in, through which it can
3069     *        access the current theme, resources, etc.
3070     */
3071    public View(Context context) {
3072        mContext = context;
3073        mResources = context != null ? context.getResources() : null;
3074        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3075        // Set layout and text direction defaults
3076        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3077                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3078                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3079                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3080        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3081        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3082        mUserPaddingStart = -1;
3083        mUserPaddingEnd = -1;
3084        mUserPaddingRelative = false;
3085    }
3086
3087    /**
3088     * Delegate for injecting accessiblity functionality.
3089     */
3090    AccessibilityDelegate mAccessibilityDelegate;
3091
3092    /**
3093     * Consistency verifier for debugging purposes.
3094     * @hide
3095     */
3096    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3097            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3098                    new InputEventConsistencyVerifier(this, 0) : null;
3099
3100    /**
3101     * Constructor that is called when inflating a view from XML. This is called
3102     * when a view is being constructed from an XML file, supplying attributes
3103     * that were specified in the XML file. This version uses a default style of
3104     * 0, so the only attribute values applied are those in the Context's Theme
3105     * and the given AttributeSet.
3106     *
3107     * <p>
3108     * The method onFinishInflate() will be called after all children have been
3109     * added.
3110     *
3111     * @param context The Context the view is running in, through which it can
3112     *        access the current theme, resources, etc.
3113     * @param attrs The attributes of the XML tag that is inflating the view.
3114     * @see #View(Context, AttributeSet, int)
3115     */
3116    public View(Context context, AttributeSet attrs) {
3117        this(context, attrs, 0);
3118    }
3119
3120    /**
3121     * Perform inflation from XML and apply a class-specific base style. This
3122     * constructor of View allows subclasses to use their own base style when
3123     * they are inflating. For example, a Button class's constructor would call
3124     * this version of the super class constructor and supply
3125     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3126     * the theme's button style to modify all of the base view attributes (in
3127     * particular its background) as well as the Button class's attributes.
3128     *
3129     * @param context The Context the view is running in, through which it can
3130     *        access the current theme, resources, etc.
3131     * @param attrs The attributes of the XML tag that is inflating the view.
3132     * @param defStyle The default style to apply to this view. If 0, no style
3133     *        will be applied (beyond what is included in the theme). This may
3134     *        either be an attribute resource, whose value will be retrieved
3135     *        from the current theme, or an explicit style resource.
3136     * @see #View(Context, AttributeSet)
3137     */
3138    public View(Context context, AttributeSet attrs, int defStyle) {
3139        this(context);
3140
3141        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3142                defStyle, 0);
3143
3144        Drawable background = null;
3145
3146        int leftPadding = -1;
3147        int topPadding = -1;
3148        int rightPadding = -1;
3149        int bottomPadding = -1;
3150        int startPadding = -1;
3151        int endPadding = -1;
3152
3153        int padding = -1;
3154
3155        int viewFlagValues = 0;
3156        int viewFlagMasks = 0;
3157
3158        boolean setScrollContainer = false;
3159
3160        int x = 0;
3161        int y = 0;
3162
3163        float tx = 0;
3164        float ty = 0;
3165        float rotation = 0;
3166        float rotationX = 0;
3167        float rotationY = 0;
3168        float sx = 1f;
3169        float sy = 1f;
3170        boolean transformSet = false;
3171
3172        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3173
3174        int overScrollMode = mOverScrollMode;
3175        final int N = a.getIndexCount();
3176        for (int i = 0; i < N; i++) {
3177            int attr = a.getIndex(i);
3178            switch (attr) {
3179                case com.android.internal.R.styleable.View_background:
3180                    background = a.getDrawable(attr);
3181                    break;
3182                case com.android.internal.R.styleable.View_padding:
3183                    padding = a.getDimensionPixelSize(attr, -1);
3184                    break;
3185                 case com.android.internal.R.styleable.View_paddingLeft:
3186                    leftPadding = a.getDimensionPixelSize(attr, -1);
3187                    break;
3188                case com.android.internal.R.styleable.View_paddingTop:
3189                    topPadding = a.getDimensionPixelSize(attr, -1);
3190                    break;
3191                case com.android.internal.R.styleable.View_paddingRight:
3192                    rightPadding = a.getDimensionPixelSize(attr, -1);
3193                    break;
3194                case com.android.internal.R.styleable.View_paddingBottom:
3195                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3196                    break;
3197                case com.android.internal.R.styleable.View_paddingStart:
3198                    startPadding = a.getDimensionPixelSize(attr, -1);
3199                    break;
3200                case com.android.internal.R.styleable.View_paddingEnd:
3201                    endPadding = a.getDimensionPixelSize(attr, -1);
3202                    break;
3203                case com.android.internal.R.styleable.View_scrollX:
3204                    x = a.getDimensionPixelOffset(attr, 0);
3205                    break;
3206                case com.android.internal.R.styleable.View_scrollY:
3207                    y = a.getDimensionPixelOffset(attr, 0);
3208                    break;
3209                case com.android.internal.R.styleable.View_alpha:
3210                    setAlpha(a.getFloat(attr, 1f));
3211                    break;
3212                case com.android.internal.R.styleable.View_transformPivotX:
3213                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3214                    break;
3215                case com.android.internal.R.styleable.View_transformPivotY:
3216                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3217                    break;
3218                case com.android.internal.R.styleable.View_translationX:
3219                    tx = a.getDimensionPixelOffset(attr, 0);
3220                    transformSet = true;
3221                    break;
3222                case com.android.internal.R.styleable.View_translationY:
3223                    ty = a.getDimensionPixelOffset(attr, 0);
3224                    transformSet = true;
3225                    break;
3226                case com.android.internal.R.styleable.View_rotation:
3227                    rotation = a.getFloat(attr, 0);
3228                    transformSet = true;
3229                    break;
3230                case com.android.internal.R.styleable.View_rotationX:
3231                    rotationX = a.getFloat(attr, 0);
3232                    transformSet = true;
3233                    break;
3234                case com.android.internal.R.styleable.View_rotationY:
3235                    rotationY = a.getFloat(attr, 0);
3236                    transformSet = true;
3237                    break;
3238                case com.android.internal.R.styleable.View_scaleX:
3239                    sx = a.getFloat(attr, 1f);
3240                    transformSet = true;
3241                    break;
3242                case com.android.internal.R.styleable.View_scaleY:
3243                    sy = a.getFloat(attr, 1f);
3244                    transformSet = true;
3245                    break;
3246                case com.android.internal.R.styleable.View_id:
3247                    mID = a.getResourceId(attr, NO_ID);
3248                    break;
3249                case com.android.internal.R.styleable.View_tag:
3250                    mTag = a.getText(attr);
3251                    break;
3252                case com.android.internal.R.styleable.View_fitsSystemWindows:
3253                    if (a.getBoolean(attr, false)) {
3254                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3255                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3256                    }
3257                    break;
3258                case com.android.internal.R.styleable.View_focusable:
3259                    if (a.getBoolean(attr, false)) {
3260                        viewFlagValues |= FOCUSABLE;
3261                        viewFlagMasks |= FOCUSABLE_MASK;
3262                    }
3263                    break;
3264                case com.android.internal.R.styleable.View_focusableInTouchMode:
3265                    if (a.getBoolean(attr, false)) {
3266                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3267                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3268                    }
3269                    break;
3270                case com.android.internal.R.styleable.View_clickable:
3271                    if (a.getBoolean(attr, false)) {
3272                        viewFlagValues |= CLICKABLE;
3273                        viewFlagMasks |= CLICKABLE;
3274                    }
3275                    break;
3276                case com.android.internal.R.styleable.View_longClickable:
3277                    if (a.getBoolean(attr, false)) {
3278                        viewFlagValues |= LONG_CLICKABLE;
3279                        viewFlagMasks |= LONG_CLICKABLE;
3280                    }
3281                    break;
3282                case com.android.internal.R.styleable.View_saveEnabled:
3283                    if (!a.getBoolean(attr, true)) {
3284                        viewFlagValues |= SAVE_DISABLED;
3285                        viewFlagMasks |= SAVE_DISABLED_MASK;
3286                    }
3287                    break;
3288                case com.android.internal.R.styleable.View_duplicateParentState:
3289                    if (a.getBoolean(attr, false)) {
3290                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3291                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3292                    }
3293                    break;
3294                case com.android.internal.R.styleable.View_visibility:
3295                    final int visibility = a.getInt(attr, 0);
3296                    if (visibility != 0) {
3297                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3298                        viewFlagMasks |= VISIBILITY_MASK;
3299                    }
3300                    break;
3301                case com.android.internal.R.styleable.View_layoutDirection:
3302                    // Clear any layout direction flags (included resolved bits) already set
3303                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3304                    // Set the layout direction flags depending on the value of the attribute
3305                    final int layoutDirection = a.getInt(attr, -1);
3306                    final int value = (layoutDirection != -1) ?
3307                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3308                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3309                    break;
3310                case com.android.internal.R.styleable.View_drawingCacheQuality:
3311                    final int cacheQuality = a.getInt(attr, 0);
3312                    if (cacheQuality != 0) {
3313                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3314                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3315                    }
3316                    break;
3317                case com.android.internal.R.styleable.View_contentDescription:
3318                    mContentDescription = a.getString(attr);
3319                    break;
3320                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3321                    if (!a.getBoolean(attr, true)) {
3322                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3323                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3324                    }
3325                    break;
3326                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3327                    if (!a.getBoolean(attr, true)) {
3328                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3329                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3330                    }
3331                    break;
3332                case R.styleable.View_scrollbars:
3333                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3334                    if (scrollbars != SCROLLBARS_NONE) {
3335                        viewFlagValues |= scrollbars;
3336                        viewFlagMasks |= SCROLLBARS_MASK;
3337                        initializeScrollbars(a);
3338                    }
3339                    break;
3340                //noinspection deprecation
3341                case R.styleable.View_fadingEdge:
3342                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3343                        // Ignore the attribute starting with ICS
3344                        break;
3345                    }
3346                    // With builds < ICS, fall through and apply fading edges
3347                case R.styleable.View_requiresFadingEdge:
3348                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3349                    if (fadingEdge != FADING_EDGE_NONE) {
3350                        viewFlagValues |= fadingEdge;
3351                        viewFlagMasks |= FADING_EDGE_MASK;
3352                        initializeFadingEdge(a);
3353                    }
3354                    break;
3355                case R.styleable.View_scrollbarStyle:
3356                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3357                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3358                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3359                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3360                    }
3361                    break;
3362                case R.styleable.View_isScrollContainer:
3363                    setScrollContainer = true;
3364                    if (a.getBoolean(attr, false)) {
3365                        setScrollContainer(true);
3366                    }
3367                    break;
3368                case com.android.internal.R.styleable.View_keepScreenOn:
3369                    if (a.getBoolean(attr, false)) {
3370                        viewFlagValues |= KEEP_SCREEN_ON;
3371                        viewFlagMasks |= KEEP_SCREEN_ON;
3372                    }
3373                    break;
3374                case R.styleable.View_filterTouchesWhenObscured:
3375                    if (a.getBoolean(attr, false)) {
3376                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3377                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3378                    }
3379                    break;
3380                case R.styleable.View_nextFocusLeft:
3381                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3382                    break;
3383                case R.styleable.View_nextFocusRight:
3384                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3385                    break;
3386                case R.styleable.View_nextFocusUp:
3387                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3388                    break;
3389                case R.styleable.View_nextFocusDown:
3390                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3391                    break;
3392                case R.styleable.View_nextFocusForward:
3393                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3394                    break;
3395                case R.styleable.View_minWidth:
3396                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3397                    break;
3398                case R.styleable.View_minHeight:
3399                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3400                    break;
3401                case R.styleable.View_onClick:
3402                    if (context.isRestricted()) {
3403                        throw new IllegalStateException("The android:onClick attribute cannot "
3404                                + "be used within a restricted context");
3405                    }
3406
3407                    final String handlerName = a.getString(attr);
3408                    if (handlerName != null) {
3409                        setOnClickListener(new OnClickListener() {
3410                            private Method mHandler;
3411
3412                            public void onClick(View v) {
3413                                if (mHandler == null) {
3414                                    try {
3415                                        mHandler = getContext().getClass().getMethod(handlerName,
3416                                                View.class);
3417                                    } catch (NoSuchMethodException e) {
3418                                        int id = getId();
3419                                        String idText = id == NO_ID ? "" : " with id '"
3420                                                + getContext().getResources().getResourceEntryName(
3421                                                    id) + "'";
3422                                        throw new IllegalStateException("Could not find a method " +
3423                                                handlerName + "(View) in the activity "
3424                                                + getContext().getClass() + " for onClick handler"
3425                                                + " on view " + View.this.getClass() + idText, e);
3426                                    }
3427                                }
3428
3429                                try {
3430                                    mHandler.invoke(getContext(), View.this);
3431                                } catch (IllegalAccessException e) {
3432                                    throw new IllegalStateException("Could not execute non "
3433                                            + "public method of the activity", e);
3434                                } catch (InvocationTargetException e) {
3435                                    throw new IllegalStateException("Could not execute "
3436                                            + "method of the activity", e);
3437                                }
3438                            }
3439                        });
3440                    }
3441                    break;
3442                case R.styleable.View_overScrollMode:
3443                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3444                    break;
3445                case R.styleable.View_verticalScrollbarPosition:
3446                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3447                    break;
3448                case R.styleable.View_layerType:
3449                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3450                    break;
3451                case R.styleable.View_textDirection:
3452                    // Clear any text direction flag already set
3453                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3454                    // Set the text direction flags depending on the value of the attribute
3455                    final int textDirection = a.getInt(attr, -1);
3456                    if (textDirection != -1) {
3457                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3458                    }
3459                    break;
3460                case R.styleable.View_textAlignment:
3461                    // Clear any text alignment flag already set
3462                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3463                    // Set the text alignment flag depending on the value of the attribute
3464                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3465                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3466                    break;
3467                case R.styleable.View_importantForAccessibility:
3468                    setImportantForAccessibility(a.getInt(attr,
3469                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3470            }
3471        }
3472
3473        a.recycle();
3474
3475        setOverScrollMode(overScrollMode);
3476
3477        if (background != null) {
3478            setBackground(background);
3479        }
3480
3481        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3482        // layout direction). Those cached values will be used later during padding resolution.
3483        mUserPaddingStart = startPadding;
3484        mUserPaddingEnd = endPadding;
3485
3486        updateUserPaddingRelative();
3487
3488        if (padding >= 0) {
3489            leftPadding = padding;
3490            topPadding = padding;
3491            rightPadding = padding;
3492            bottomPadding = padding;
3493        }
3494
3495        // If the user specified the padding (either with android:padding or
3496        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3497        // use the default padding or the padding from the background drawable
3498        // (stored at this point in mPadding*)
3499        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3500                topPadding >= 0 ? topPadding : mPaddingTop,
3501                rightPadding >= 0 ? rightPadding : mPaddingRight,
3502                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3503
3504        if (viewFlagMasks != 0) {
3505            setFlags(viewFlagValues, viewFlagMasks);
3506        }
3507
3508        // Needs to be called after mViewFlags is set
3509        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3510            recomputePadding();
3511        }
3512
3513        if (x != 0 || y != 0) {
3514            scrollTo(x, y);
3515        }
3516
3517        if (transformSet) {
3518            setTranslationX(tx);
3519            setTranslationY(ty);
3520            setRotation(rotation);
3521            setRotationX(rotationX);
3522            setRotationY(rotationY);
3523            setScaleX(sx);
3524            setScaleY(sy);
3525        }
3526
3527        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3528            setScrollContainer(true);
3529        }
3530
3531        computeOpaqueFlags();
3532    }
3533
3534    private void updateUserPaddingRelative() {
3535        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3536    }
3537
3538    /**
3539     * Non-public constructor for use in testing
3540     */
3541    View() {
3542        mResources = null;
3543    }
3544
3545    /**
3546     * <p>
3547     * Initializes the fading edges from a given set of styled attributes. This
3548     * method should be called by subclasses that need fading edges and when an
3549     * instance of these subclasses is created programmatically rather than
3550     * being inflated from XML. This method is automatically called when the XML
3551     * is inflated.
3552     * </p>
3553     *
3554     * @param a the styled attributes set to initialize the fading edges from
3555     */
3556    protected void initializeFadingEdge(TypedArray a) {
3557        initScrollCache();
3558
3559        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3560                R.styleable.View_fadingEdgeLength,
3561                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3562    }
3563
3564    /**
3565     * Returns the size of the vertical faded edges used to indicate that more
3566     * content in this view is visible.
3567     *
3568     * @return The size in pixels of the vertical faded edge or 0 if vertical
3569     *         faded edges are not enabled for this view.
3570     * @attr ref android.R.styleable#View_fadingEdgeLength
3571     */
3572    public int getVerticalFadingEdgeLength() {
3573        if (isVerticalFadingEdgeEnabled()) {
3574            ScrollabilityCache cache = mScrollCache;
3575            if (cache != null) {
3576                return cache.fadingEdgeLength;
3577            }
3578        }
3579        return 0;
3580    }
3581
3582    /**
3583     * Set the size of the faded edge used to indicate that more content in this
3584     * view is available.  Will not change whether the fading edge is enabled; use
3585     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3586     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3587     * for the vertical or horizontal fading edges.
3588     *
3589     * @param length The size in pixels of the faded edge used to indicate that more
3590     *        content in this view is visible.
3591     */
3592    public void setFadingEdgeLength(int length) {
3593        initScrollCache();
3594        mScrollCache.fadingEdgeLength = length;
3595    }
3596
3597    /**
3598     * Returns the size of the horizontal faded edges used to indicate that more
3599     * content in this view is visible.
3600     *
3601     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3602     *         faded edges are not enabled for this view.
3603     * @attr ref android.R.styleable#View_fadingEdgeLength
3604     */
3605    public int getHorizontalFadingEdgeLength() {
3606        if (isHorizontalFadingEdgeEnabled()) {
3607            ScrollabilityCache cache = mScrollCache;
3608            if (cache != null) {
3609                return cache.fadingEdgeLength;
3610            }
3611        }
3612        return 0;
3613    }
3614
3615    /**
3616     * Returns the width of the vertical scrollbar.
3617     *
3618     * @return The width in pixels of the vertical scrollbar or 0 if there
3619     *         is no vertical scrollbar.
3620     */
3621    public int getVerticalScrollbarWidth() {
3622        ScrollabilityCache cache = mScrollCache;
3623        if (cache != null) {
3624            ScrollBarDrawable scrollBar = cache.scrollBar;
3625            if (scrollBar != null) {
3626                int size = scrollBar.getSize(true);
3627                if (size <= 0) {
3628                    size = cache.scrollBarSize;
3629                }
3630                return size;
3631            }
3632            return 0;
3633        }
3634        return 0;
3635    }
3636
3637    /**
3638     * Returns the height of the horizontal scrollbar.
3639     *
3640     * @return The height in pixels of the horizontal scrollbar or 0 if
3641     *         there is no horizontal scrollbar.
3642     */
3643    protected int getHorizontalScrollbarHeight() {
3644        ScrollabilityCache cache = mScrollCache;
3645        if (cache != null) {
3646            ScrollBarDrawable scrollBar = cache.scrollBar;
3647            if (scrollBar != null) {
3648                int size = scrollBar.getSize(false);
3649                if (size <= 0) {
3650                    size = cache.scrollBarSize;
3651                }
3652                return size;
3653            }
3654            return 0;
3655        }
3656        return 0;
3657    }
3658
3659    /**
3660     * <p>
3661     * Initializes the scrollbars from a given set of styled attributes. This
3662     * method should be called by subclasses that need scrollbars and when an
3663     * instance of these subclasses is created programmatically rather than
3664     * being inflated from XML. This method is automatically called when the XML
3665     * is inflated.
3666     * </p>
3667     *
3668     * @param a the styled attributes set to initialize the scrollbars from
3669     */
3670    protected void initializeScrollbars(TypedArray a) {
3671        initScrollCache();
3672
3673        final ScrollabilityCache scrollabilityCache = mScrollCache;
3674
3675        if (scrollabilityCache.scrollBar == null) {
3676            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3677        }
3678
3679        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3680
3681        if (!fadeScrollbars) {
3682            scrollabilityCache.state = ScrollabilityCache.ON;
3683        }
3684        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3685
3686
3687        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3688                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3689                        .getScrollBarFadeDuration());
3690        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3691                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3692                ViewConfiguration.getScrollDefaultDelay());
3693
3694
3695        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3696                com.android.internal.R.styleable.View_scrollbarSize,
3697                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3698
3699        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3700        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3701
3702        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3703        if (thumb != null) {
3704            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3705        }
3706
3707        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3708                false);
3709        if (alwaysDraw) {
3710            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3711        }
3712
3713        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3714        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3715
3716        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3717        if (thumb != null) {
3718            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3719        }
3720
3721        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3722                false);
3723        if (alwaysDraw) {
3724            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3725        }
3726
3727        // Re-apply user/background padding so that scrollbar(s) get added
3728        resolvePadding();
3729    }
3730
3731    /**
3732     * <p>
3733     * Initalizes the scrollability cache if necessary.
3734     * </p>
3735     */
3736    private void initScrollCache() {
3737        if (mScrollCache == null) {
3738            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3739        }
3740    }
3741
3742    private ScrollabilityCache getScrollCache() {
3743        initScrollCache();
3744        return mScrollCache;
3745    }
3746
3747    /**
3748     * Set the position of the vertical scroll bar. Should be one of
3749     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3750     * {@link #SCROLLBAR_POSITION_RIGHT}.
3751     *
3752     * @param position Where the vertical scroll bar should be positioned.
3753     */
3754    public void setVerticalScrollbarPosition(int position) {
3755        if (mVerticalScrollbarPosition != position) {
3756            mVerticalScrollbarPosition = position;
3757            computeOpaqueFlags();
3758            resolvePadding();
3759        }
3760    }
3761
3762    /**
3763     * @return The position where the vertical scroll bar will show, if applicable.
3764     * @see #setVerticalScrollbarPosition(int)
3765     */
3766    public int getVerticalScrollbarPosition() {
3767        return mVerticalScrollbarPosition;
3768    }
3769
3770    ListenerInfo getListenerInfo() {
3771        if (mListenerInfo != null) {
3772            return mListenerInfo;
3773        }
3774        mListenerInfo = new ListenerInfo();
3775        return mListenerInfo;
3776    }
3777
3778    /**
3779     * Register a callback to be invoked when focus of this view changed.
3780     *
3781     * @param l The callback that will run.
3782     */
3783    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3784        getListenerInfo().mOnFocusChangeListener = l;
3785    }
3786
3787    /**
3788     * Add a listener that will be called when the bounds of the view change due to
3789     * layout processing.
3790     *
3791     * @param listener The listener that will be called when layout bounds change.
3792     */
3793    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3794        ListenerInfo li = getListenerInfo();
3795        if (li.mOnLayoutChangeListeners == null) {
3796            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3797        }
3798        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3799            li.mOnLayoutChangeListeners.add(listener);
3800        }
3801    }
3802
3803    /**
3804     * Remove a listener for layout changes.
3805     *
3806     * @param listener The listener for layout bounds change.
3807     */
3808    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3809        ListenerInfo li = mListenerInfo;
3810        if (li == null || li.mOnLayoutChangeListeners == null) {
3811            return;
3812        }
3813        li.mOnLayoutChangeListeners.remove(listener);
3814    }
3815
3816    /**
3817     * Add a listener for attach state changes.
3818     *
3819     * This listener will be called whenever this view is attached or detached
3820     * from a window. Remove the listener using
3821     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3822     *
3823     * @param listener Listener to attach
3824     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3825     */
3826    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3827        ListenerInfo li = getListenerInfo();
3828        if (li.mOnAttachStateChangeListeners == null) {
3829            li.mOnAttachStateChangeListeners
3830                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3831        }
3832        li.mOnAttachStateChangeListeners.add(listener);
3833    }
3834
3835    /**
3836     * Remove a listener for attach state changes. The listener will receive no further
3837     * notification of window attach/detach events.
3838     *
3839     * @param listener Listener to remove
3840     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3841     */
3842    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3843        ListenerInfo li = mListenerInfo;
3844        if (li == null || li.mOnAttachStateChangeListeners == null) {
3845            return;
3846        }
3847        li.mOnAttachStateChangeListeners.remove(listener);
3848    }
3849
3850    /**
3851     * Returns the focus-change callback registered for this view.
3852     *
3853     * @return The callback, or null if one is not registered.
3854     */
3855    public OnFocusChangeListener getOnFocusChangeListener() {
3856        ListenerInfo li = mListenerInfo;
3857        return li != null ? li.mOnFocusChangeListener : null;
3858    }
3859
3860    /**
3861     * Register a callback to be invoked when this view is clicked. If this view is not
3862     * clickable, it becomes clickable.
3863     *
3864     * @param l The callback that will run
3865     *
3866     * @see #setClickable(boolean)
3867     */
3868    public void setOnClickListener(OnClickListener l) {
3869        if (!isClickable()) {
3870            setClickable(true);
3871        }
3872        getListenerInfo().mOnClickListener = l;
3873    }
3874
3875    /**
3876     * Return whether this view has an attached OnClickListener.  Returns
3877     * true if there is a listener, false if there is none.
3878     */
3879    public boolean hasOnClickListeners() {
3880        ListenerInfo li = mListenerInfo;
3881        return (li != null && li.mOnClickListener != null);
3882    }
3883
3884    /**
3885     * Register a callback to be invoked when this view is clicked and held. If this view is not
3886     * long clickable, it becomes long clickable.
3887     *
3888     * @param l The callback that will run
3889     *
3890     * @see #setLongClickable(boolean)
3891     */
3892    public void setOnLongClickListener(OnLongClickListener l) {
3893        if (!isLongClickable()) {
3894            setLongClickable(true);
3895        }
3896        getListenerInfo().mOnLongClickListener = l;
3897    }
3898
3899    /**
3900     * Register a callback to be invoked when the context menu for this view is
3901     * being built. If this view is not long clickable, it becomes long clickable.
3902     *
3903     * @param l The callback that will run
3904     *
3905     */
3906    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3907        if (!isLongClickable()) {
3908            setLongClickable(true);
3909        }
3910        getListenerInfo().mOnCreateContextMenuListener = l;
3911    }
3912
3913    /**
3914     * Call this view's OnClickListener, if it is defined.  Performs all normal
3915     * actions associated with clicking: reporting accessibility event, playing
3916     * a sound, etc.
3917     *
3918     * @return True there was an assigned OnClickListener that was called, false
3919     *         otherwise is returned.
3920     */
3921    public boolean performClick() {
3922        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3923
3924        ListenerInfo li = mListenerInfo;
3925        if (li != null && li.mOnClickListener != null) {
3926            playSoundEffect(SoundEffectConstants.CLICK);
3927            li.mOnClickListener.onClick(this);
3928            return true;
3929        }
3930
3931        return false;
3932    }
3933
3934    /**
3935     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3936     * this only calls the listener, and does not do any associated clicking
3937     * actions like reporting an accessibility event.
3938     *
3939     * @return True there was an assigned OnClickListener that was called, false
3940     *         otherwise is returned.
3941     */
3942    public boolean callOnClick() {
3943        ListenerInfo li = mListenerInfo;
3944        if (li != null && li.mOnClickListener != null) {
3945            li.mOnClickListener.onClick(this);
3946            return true;
3947        }
3948        return false;
3949    }
3950
3951    /**
3952     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3953     * OnLongClickListener did not consume the event.
3954     *
3955     * @return True if one of the above receivers consumed the event, false otherwise.
3956     */
3957    public boolean performLongClick() {
3958        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3959
3960        boolean handled = false;
3961        ListenerInfo li = mListenerInfo;
3962        if (li != null && li.mOnLongClickListener != null) {
3963            handled = li.mOnLongClickListener.onLongClick(View.this);
3964        }
3965        if (!handled) {
3966            handled = showContextMenu();
3967        }
3968        if (handled) {
3969            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3970        }
3971        return handled;
3972    }
3973
3974    /**
3975     * Performs button-related actions during a touch down event.
3976     *
3977     * @param event The event.
3978     * @return True if the down was consumed.
3979     *
3980     * @hide
3981     */
3982    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3983        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3984            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3985                return true;
3986            }
3987        }
3988        return false;
3989    }
3990
3991    /**
3992     * Bring up the context menu for this view.
3993     *
3994     * @return Whether a context menu was displayed.
3995     */
3996    public boolean showContextMenu() {
3997        return getParent().showContextMenuForChild(this);
3998    }
3999
4000    /**
4001     * Bring up the context menu for this view, referring to the item under the specified point.
4002     *
4003     * @param x The referenced x coordinate.
4004     * @param y The referenced y coordinate.
4005     * @param metaState The keyboard modifiers that were pressed.
4006     * @return Whether a context menu was displayed.
4007     *
4008     * @hide
4009     */
4010    public boolean showContextMenu(float x, float y, int metaState) {
4011        return showContextMenu();
4012    }
4013
4014    /**
4015     * Start an action mode.
4016     *
4017     * @param callback Callback that will control the lifecycle of the action mode
4018     * @return The new action mode if it is started, null otherwise
4019     *
4020     * @see ActionMode
4021     */
4022    public ActionMode startActionMode(ActionMode.Callback callback) {
4023        ViewParent parent = getParent();
4024        if (parent == null) return null;
4025        return parent.startActionModeForChild(this, callback);
4026    }
4027
4028    /**
4029     * Register a callback to be invoked when a key is pressed in this view.
4030     * @param l the key listener to attach to this view
4031     */
4032    public void setOnKeyListener(OnKeyListener l) {
4033        getListenerInfo().mOnKeyListener = l;
4034    }
4035
4036    /**
4037     * Register a callback to be invoked when a touch event is sent to this view.
4038     * @param l the touch listener to attach to this view
4039     */
4040    public void setOnTouchListener(OnTouchListener l) {
4041        getListenerInfo().mOnTouchListener = l;
4042    }
4043
4044    /**
4045     * Register a callback to be invoked when a generic motion event is sent to this view.
4046     * @param l the generic motion listener to attach to this view
4047     */
4048    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4049        getListenerInfo().mOnGenericMotionListener = l;
4050    }
4051
4052    /**
4053     * Register a callback to be invoked when a hover event is sent to this view.
4054     * @param l the hover listener to attach to this view
4055     */
4056    public void setOnHoverListener(OnHoverListener l) {
4057        getListenerInfo().mOnHoverListener = l;
4058    }
4059
4060    /**
4061     * Register a drag event listener callback object for this View. The parameter is
4062     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4063     * View, the system calls the
4064     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4065     * @param l An implementation of {@link android.view.View.OnDragListener}.
4066     */
4067    public void setOnDragListener(OnDragListener l) {
4068        getListenerInfo().mOnDragListener = l;
4069    }
4070
4071    /**
4072     * Give this view focus. This will cause
4073     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4074     *
4075     * Note: this does not check whether this {@link View} should get focus, it just
4076     * gives it focus no matter what.  It should only be called internally by framework
4077     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4078     *
4079     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4080     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4081     *        focus moved when requestFocus() is called. It may not always
4082     *        apply, in which case use the default View.FOCUS_DOWN.
4083     * @param previouslyFocusedRect The rectangle of the view that had focus
4084     *        prior in this View's coordinate system.
4085     */
4086    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4087        if (DBG) {
4088            System.out.println(this + " requestFocus()");
4089        }
4090
4091        if ((mPrivateFlags & FOCUSED) == 0) {
4092            mPrivateFlags |= FOCUSED;
4093
4094            if (mParent != null) {
4095                mParent.requestChildFocus(this, this);
4096            }
4097
4098            onFocusChanged(true, direction, previouslyFocusedRect);
4099            refreshDrawableState();
4100
4101            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4102                notifyAccessibilityStateChanged();
4103            }
4104        }
4105    }
4106
4107    /**
4108     * Request that a rectangle of this view be visible on the screen,
4109     * scrolling if necessary just enough.
4110     *
4111     * <p>A View should call this if it maintains some notion of which part
4112     * of its content is interesting.  For example, a text editing view
4113     * should call this when its cursor moves.
4114     *
4115     * @param rectangle The rectangle.
4116     * @return Whether any parent scrolled.
4117     */
4118    public boolean requestRectangleOnScreen(Rect rectangle) {
4119        return requestRectangleOnScreen(rectangle, false);
4120    }
4121
4122    /**
4123     * Request that a rectangle of this view be visible on the screen,
4124     * scrolling if necessary just enough.
4125     *
4126     * <p>A View should call this if it maintains some notion of which part
4127     * of its content is interesting.  For example, a text editing view
4128     * should call this when its cursor moves.
4129     *
4130     * <p>When <code>immediate</code> is set to true, scrolling will not be
4131     * animated.
4132     *
4133     * @param rectangle The rectangle.
4134     * @param immediate True to forbid animated scrolling, false otherwise
4135     * @return Whether any parent scrolled.
4136     */
4137    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4138        View child = this;
4139        ViewParent parent = mParent;
4140        boolean scrolled = false;
4141        while (parent != null) {
4142            scrolled |= parent.requestChildRectangleOnScreen(child,
4143                    rectangle, immediate);
4144
4145            // offset rect so next call has the rectangle in the
4146            // coordinate system of its direct child.
4147            rectangle.offset(child.getLeft(), child.getTop());
4148            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4149
4150            if (!(parent instanceof View)) {
4151                break;
4152            }
4153
4154            child = (View) parent;
4155            parent = child.getParent();
4156        }
4157        return scrolled;
4158    }
4159
4160    /**
4161     * Called when this view wants to give up focus. If focus is cleared
4162     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4163     * <p>
4164     * <strong>Note:</strong> When a View clears focus the framework is trying
4165     * to give focus to the first focusable View from the top. Hence, if this
4166     * View is the first from the top that can take focus, then all callbacks
4167     * related to clearing focus will be invoked after wich the framework will
4168     * give focus to this view.
4169     * </p>
4170     */
4171    public void clearFocus() {
4172        if (DBG) {
4173            System.out.println(this + " clearFocus()");
4174        }
4175
4176        if ((mPrivateFlags & FOCUSED) != 0) {
4177            mPrivateFlags &= ~FOCUSED;
4178
4179            if (mParent != null) {
4180                mParent.clearChildFocus(this);
4181            }
4182
4183            onFocusChanged(false, 0, null);
4184
4185            refreshDrawableState();
4186
4187            ensureInputFocusOnFirstFocusable();
4188
4189            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4190                notifyAccessibilityStateChanged();
4191            }
4192        }
4193    }
4194
4195    void ensureInputFocusOnFirstFocusable() {
4196        View root = getRootView();
4197        if (root != null) {
4198            root.requestFocus();
4199        }
4200    }
4201
4202    /**
4203     * Called internally by the view system when a new view is getting focus.
4204     * This is what clears the old focus.
4205     */
4206    void unFocus() {
4207        if (DBG) {
4208            System.out.println(this + " unFocus()");
4209        }
4210
4211        if ((mPrivateFlags & FOCUSED) != 0) {
4212            mPrivateFlags &= ~FOCUSED;
4213
4214            onFocusChanged(false, 0, null);
4215            refreshDrawableState();
4216
4217            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4218                notifyAccessibilityStateChanged();
4219            }
4220        }
4221    }
4222
4223    /**
4224     * Returns true if this view has focus iteself, or is the ancestor of the
4225     * view that has focus.
4226     *
4227     * @return True if this view has or contains focus, false otherwise.
4228     */
4229    @ViewDebug.ExportedProperty(category = "focus")
4230    public boolean hasFocus() {
4231        return (mPrivateFlags & FOCUSED) != 0;
4232    }
4233
4234    /**
4235     * Returns true if this view is focusable or if it contains a reachable View
4236     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4237     * is a View whose parents do not block descendants focus.
4238     *
4239     * Only {@link #VISIBLE} views are considered focusable.
4240     *
4241     * @return True if the view is focusable or if the view contains a focusable
4242     *         View, false otherwise.
4243     *
4244     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4245     */
4246    public boolean hasFocusable() {
4247        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4248    }
4249
4250    /**
4251     * Called by the view system when the focus state of this view changes.
4252     * When the focus change event is caused by directional navigation, direction
4253     * and previouslyFocusedRect provide insight into where the focus is coming from.
4254     * When overriding, be sure to call up through to the super class so that
4255     * the standard focus handling will occur.
4256     *
4257     * @param gainFocus True if the View has focus; false otherwise.
4258     * @param direction The direction focus has moved when requestFocus()
4259     *                  is called to give this view focus. Values are
4260     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4261     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4262     *                  It may not always apply, in which case use the default.
4263     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4264     *        system, of the previously focused view.  If applicable, this will be
4265     *        passed in as finer grained information about where the focus is coming
4266     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4267     */
4268    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4269        if (gainFocus) {
4270            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4271                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4272                requestAccessibilityFocus();
4273            }
4274        }
4275
4276        InputMethodManager imm = InputMethodManager.peekInstance();
4277        if (!gainFocus) {
4278            if (isPressed()) {
4279                setPressed(false);
4280            }
4281            if (imm != null && mAttachInfo != null
4282                    && mAttachInfo.mHasWindowFocus) {
4283                imm.focusOut(this);
4284            }
4285            onFocusLost();
4286        } else if (imm != null && mAttachInfo != null
4287                && mAttachInfo.mHasWindowFocus) {
4288            imm.focusIn(this);
4289        }
4290
4291        invalidate(true);
4292        ListenerInfo li = mListenerInfo;
4293        if (li != null && li.mOnFocusChangeListener != null) {
4294            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4295        }
4296
4297        if (mAttachInfo != null) {
4298            mAttachInfo.mKeyDispatchState.reset(this);
4299        }
4300    }
4301
4302    /**
4303     * Sends an accessibility event of the given type. If accessiiblity is
4304     * not enabled this method has no effect. The default implementation calls
4305     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4306     * to populate information about the event source (this View), then calls
4307     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4308     * populate the text content of the event source including its descendants,
4309     * and last calls
4310     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4311     * on its parent to resuest sending of the event to interested parties.
4312     * <p>
4313     * If an {@link AccessibilityDelegate} has been specified via calling
4314     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4315     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4316     * responsible for handling this call.
4317     * </p>
4318     *
4319     * @param eventType The type of the event to send, as defined by several types from
4320     * {@link android.view.accessibility.AccessibilityEvent}, such as
4321     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4322     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4323     *
4324     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4325     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4326     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4327     * @see AccessibilityDelegate
4328     */
4329    public void sendAccessibilityEvent(int eventType) {
4330        if (mAccessibilityDelegate != null) {
4331            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4332        } else {
4333            sendAccessibilityEventInternal(eventType);
4334        }
4335    }
4336
4337    /**
4338     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4339     * {@link AccessibilityEvent} to make an announcement which is related to some
4340     * sort of a context change for which none of the events representing UI transitions
4341     * is a good fit. For example, announcing a new page in a book. If accessibility
4342     * is not enabled this method does nothing.
4343     *
4344     * @param text The announcement text.
4345     */
4346    public void announceForAccessibility(CharSequence text) {
4347        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4348            AccessibilityEvent event = AccessibilityEvent.obtain(
4349                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4350            event.getText().add(text);
4351            sendAccessibilityEventUnchecked(event);
4352        }
4353    }
4354
4355    /**
4356     * @see #sendAccessibilityEvent(int)
4357     *
4358     * Note: Called from the default {@link AccessibilityDelegate}.
4359     */
4360    void sendAccessibilityEventInternal(int eventType) {
4361        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4362            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4363        }
4364    }
4365
4366    /**
4367     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4368     * takes as an argument an empty {@link AccessibilityEvent} and does not
4369     * perform a check whether accessibility is enabled.
4370     * <p>
4371     * If an {@link AccessibilityDelegate} has been specified via calling
4372     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4373     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4374     * is responsible for handling this call.
4375     * </p>
4376     *
4377     * @param event The event to send.
4378     *
4379     * @see #sendAccessibilityEvent(int)
4380     */
4381    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4382        if (mAccessibilityDelegate != null) {
4383            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4384        } else {
4385            sendAccessibilityEventUncheckedInternal(event);
4386        }
4387    }
4388
4389    /**
4390     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4391     *
4392     * Note: Called from the default {@link AccessibilityDelegate}.
4393     */
4394    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4395        if (!isShown()) {
4396            return;
4397        }
4398        onInitializeAccessibilityEvent(event);
4399        // Only a subset of accessibility events populates text content.
4400        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4401            dispatchPopulateAccessibilityEvent(event);
4402        }
4403        // Intercept accessibility focus events fired by virtual nodes to keep
4404        // track of accessibility focus position in such nodes.
4405        final int eventType = event.getEventType();
4406        switch (eventType) {
4407            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4408                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4409                        event.getSourceNodeId());
4410                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4411                    ViewRootImpl viewRootImpl = getViewRootImpl();
4412                    if (viewRootImpl != null) {
4413                        viewRootImpl.setAccessibilityFocusedHost(this);
4414                    }
4415                }
4416            } break;
4417            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4418                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4419                        event.getSourceNodeId());
4420                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4421                    ViewRootImpl viewRootImpl = getViewRootImpl();
4422                    if (viewRootImpl != null) {
4423                        viewRootImpl.setAccessibilityFocusedHost(null);
4424                    }
4425                }
4426            } break;
4427        }
4428        // In the beginning we called #isShown(), so we know that getParent() is not null.
4429        getParent().requestSendAccessibilityEvent(this, event);
4430    }
4431
4432    /**
4433     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4434     * to its children for adding their text content to the event. Note that the
4435     * event text is populated in a separate dispatch path since we add to the
4436     * event not only the text of the source but also the text of all its descendants.
4437     * A typical implementation will call
4438     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4439     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4440     * on each child. Override this method if custom population of the event text
4441     * content is required.
4442     * <p>
4443     * If an {@link AccessibilityDelegate} has been specified via calling
4444     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4445     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4446     * is responsible for handling this call.
4447     * </p>
4448     * <p>
4449     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4450     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4451     * </p>
4452     *
4453     * @param event The event.
4454     *
4455     * @return True if the event population was completed.
4456     */
4457    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4458        if (mAccessibilityDelegate != null) {
4459            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4460        } else {
4461            return dispatchPopulateAccessibilityEventInternal(event);
4462        }
4463    }
4464
4465    /**
4466     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4467     *
4468     * Note: Called from the default {@link AccessibilityDelegate}.
4469     */
4470    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4471        onPopulateAccessibilityEvent(event);
4472        return false;
4473    }
4474
4475    /**
4476     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4477     * giving a chance to this View to populate the accessibility event with its
4478     * text content. While this method is free to modify event
4479     * attributes other than text content, doing so should normally be performed in
4480     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4481     * <p>
4482     * Example: Adding formatted date string to an accessibility event in addition
4483     *          to the text added by the super implementation:
4484     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4485     *     super.onPopulateAccessibilityEvent(event);
4486     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4487     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4488     *         mCurrentDate.getTimeInMillis(), flags);
4489     *     event.getText().add(selectedDateUtterance);
4490     * }</pre>
4491     * <p>
4492     * If an {@link AccessibilityDelegate} has been specified via calling
4493     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4494     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4495     * is responsible for handling this call.
4496     * </p>
4497     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4498     * information to the event, in case the default implementation has basic information to add.
4499     * </p>
4500     *
4501     * @param event The accessibility event which to populate.
4502     *
4503     * @see #sendAccessibilityEvent(int)
4504     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4505     */
4506    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4507        if (mAccessibilityDelegate != null) {
4508            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4509        } else {
4510            onPopulateAccessibilityEventInternal(event);
4511        }
4512    }
4513
4514    /**
4515     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4516     *
4517     * Note: Called from the default {@link AccessibilityDelegate}.
4518     */
4519    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4520
4521    }
4522
4523    /**
4524     * Initializes an {@link AccessibilityEvent} with information about
4525     * this View which is the event source. In other words, the source of
4526     * an accessibility event is the view whose state change triggered firing
4527     * the event.
4528     * <p>
4529     * Example: Setting the password property of an event in addition
4530     *          to properties set by the super implementation:
4531     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4532     *     super.onInitializeAccessibilityEvent(event);
4533     *     event.setPassword(true);
4534     * }</pre>
4535     * <p>
4536     * If an {@link AccessibilityDelegate} has been specified via calling
4537     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4538     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4539     * is responsible for handling this call.
4540     * </p>
4541     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4542     * information to the event, in case the default implementation has basic information to add.
4543     * </p>
4544     * @param event The event to initialize.
4545     *
4546     * @see #sendAccessibilityEvent(int)
4547     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4548     */
4549    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4550        if (mAccessibilityDelegate != null) {
4551            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4552        } else {
4553            onInitializeAccessibilityEventInternal(event);
4554        }
4555    }
4556
4557    /**
4558     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4559     *
4560     * Note: Called from the default {@link AccessibilityDelegate}.
4561     */
4562    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4563        event.setSource(this);
4564        event.setClassName(View.class.getName());
4565        event.setPackageName(getContext().getPackageName());
4566        event.setEnabled(isEnabled());
4567        event.setContentDescription(mContentDescription);
4568
4569        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4570            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4571            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4572                    FOCUSABLES_ALL);
4573            event.setItemCount(focusablesTempList.size());
4574            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4575            focusablesTempList.clear();
4576        }
4577    }
4578
4579    /**
4580     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4581     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4582     * This method is responsible for obtaining an accessibility node info from a
4583     * pool of reusable instances and calling
4584     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4585     * initialize the former.
4586     * <p>
4587     * Note: The client is responsible for recycling the obtained instance by calling
4588     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4589     * </p>
4590     *
4591     * @return A populated {@link AccessibilityNodeInfo}.
4592     *
4593     * @see AccessibilityNodeInfo
4594     */
4595    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4596        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4597        if (provider != null) {
4598            return provider.createAccessibilityNodeInfo(View.NO_ID);
4599        } else {
4600            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4601            onInitializeAccessibilityNodeInfo(info);
4602            return info;
4603        }
4604    }
4605
4606    /**
4607     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4608     * The base implementation sets:
4609     * <ul>
4610     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4611     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4612     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4613     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4614     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4615     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4616     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4617     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4618     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4619     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4620     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4621     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4622     * </ul>
4623     * <p>
4624     * Subclasses should override this method, call the super implementation,
4625     * and set additional attributes.
4626     * </p>
4627     * <p>
4628     * If an {@link AccessibilityDelegate} has been specified via calling
4629     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4630     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4631     * is responsible for handling this call.
4632     * </p>
4633     *
4634     * @param info The instance to initialize.
4635     */
4636    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4637        if (mAccessibilityDelegate != null) {
4638            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4639        } else {
4640            onInitializeAccessibilityNodeInfoInternal(info);
4641        }
4642    }
4643
4644    /**
4645     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4646     *
4647     * Note: Called from the default {@link AccessibilityDelegate}.
4648     */
4649    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4650        Rect bounds = mAttachInfo.mTmpInvalRect;
4651        getDrawingRect(bounds);
4652        info.setBoundsInParent(bounds);
4653
4654        getGlobalVisibleRect(bounds);
4655        bounds.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4656        info.setBoundsInScreen(bounds);
4657
4658        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4659            ViewParent parent = getParentForAccessibility();
4660            if (parent instanceof View) {
4661                info.setParent((View) parent);
4662            }
4663        }
4664
4665        info.setPackageName(mContext.getPackageName());
4666        info.setClassName(View.class.getName());
4667        info.setContentDescription(getContentDescription());
4668
4669        info.setEnabled(isEnabled());
4670        info.setClickable(isClickable());
4671        info.setFocusable(isFocusable());
4672        info.setFocused(isFocused());
4673        info.setAccessibilityFocused(isAccessibilityFocused());
4674        info.setSelected(isSelected());
4675        info.setLongClickable(isLongClickable());
4676
4677        // TODO: These make sense only if we are in an AdapterView but all
4678        // views can be selected. Maybe from accessiiblity perspective
4679        // we should report as selectable view in an AdapterView.
4680        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4681        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4682
4683        if (isFocusable()) {
4684            if (isFocused()) {
4685                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4686            } else {
4687                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4688            }
4689        }
4690
4691        info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4692        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4693
4694        if (isClickable()) {
4695            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4696        }
4697
4698        if (isLongClickable()) {
4699            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4700        }
4701
4702        if (getContentDescription() != null) {
4703            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_GRANULARITY);
4704            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_GRANULARITY);
4705            info.setGranularities(AccessibilityNodeInfo.GRANULARITY_CHARACTER
4706                    | AccessibilityNodeInfo.GRANULARITY_WORD);
4707        }
4708    }
4709
4710    /**
4711     * Computes whether this view is visible on the screen.
4712     *
4713     * @return Whether the view is visible on the screen.
4714     */
4715    boolean isDisplayedOnScreen() {
4716        // The first two checks are made also made by isShown() which
4717        // however traverses the tree up to the parent to catch that.
4718        // Therefore, we do some fail fast check to minimize the up
4719        // tree traversal.
4720        return (mAttachInfo != null
4721                && mAttachInfo.mWindowVisibility == View.VISIBLE
4722                && getAlpha() > 0
4723                && isShown()
4724                && getGlobalVisibleRect(mAttachInfo.mTmpInvalRect));
4725    }
4726
4727    /**
4728     * Sets a delegate for implementing accessibility support via compositon as
4729     * opposed to inheritance. The delegate's primary use is for implementing
4730     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4731     *
4732     * @param delegate The delegate instance.
4733     *
4734     * @see AccessibilityDelegate
4735     */
4736    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4737        mAccessibilityDelegate = delegate;
4738    }
4739
4740    /**
4741     * Gets the provider for managing a virtual view hierarchy rooted at this View
4742     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4743     * that explore the window content.
4744     * <p>
4745     * If this method returns an instance, this instance is responsible for managing
4746     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4747     * View including the one representing the View itself. Similarly the returned
4748     * instance is responsible for performing accessibility actions on any virtual
4749     * view or the root view itself.
4750     * </p>
4751     * <p>
4752     * If an {@link AccessibilityDelegate} has been specified via calling
4753     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4754     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4755     * is responsible for handling this call.
4756     * </p>
4757     *
4758     * @return The provider.
4759     *
4760     * @see AccessibilityNodeProvider
4761     */
4762    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4763        if (mAccessibilityDelegate != null) {
4764            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4765        } else {
4766            return null;
4767        }
4768    }
4769
4770    /**
4771     * Gets the unique identifier of this view on the screen for accessibility purposes.
4772     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4773     *
4774     * @return The view accessibility id.
4775     *
4776     * @hide
4777     */
4778    public int getAccessibilityViewId() {
4779        if (mAccessibilityViewId == NO_ID) {
4780            mAccessibilityViewId = sNextAccessibilityViewId++;
4781        }
4782        return mAccessibilityViewId;
4783    }
4784
4785    /**
4786     * Gets the unique identifier of the window in which this View reseides.
4787     *
4788     * @return The window accessibility id.
4789     *
4790     * @hide
4791     */
4792    public int getAccessibilityWindowId() {
4793        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4794    }
4795
4796    /**
4797     * Gets the {@link View} description. It briefly describes the view and is
4798     * primarily used for accessibility support. Set this property to enable
4799     * better accessibility support for your application. This is especially
4800     * true for views that do not have textual representation (For example,
4801     * ImageButton).
4802     *
4803     * @return The content description.
4804     *
4805     * @attr ref android.R.styleable#View_contentDescription
4806     */
4807    @ViewDebug.ExportedProperty(category = "accessibility")
4808    public CharSequence getContentDescription() {
4809        return mContentDescription;
4810    }
4811
4812    /**
4813     * Sets the {@link View} description. It briefly describes the view and is
4814     * primarily used for accessibility support. Set this property to enable
4815     * better accessibility support for your application. This is especially
4816     * true for views that do not have textual representation (For example,
4817     * ImageButton).
4818     *
4819     * @param contentDescription The content description.
4820     *
4821     * @attr ref android.R.styleable#View_contentDescription
4822     */
4823    @RemotableViewMethod
4824    public void setContentDescription(CharSequence contentDescription) {
4825        mContentDescription = contentDescription;
4826    }
4827
4828    /**
4829     * Invoked whenever this view loses focus, either by losing window focus or by losing
4830     * focus within its window. This method can be used to clear any state tied to the
4831     * focus. For instance, if a button is held pressed with the trackball and the window
4832     * loses focus, this method can be used to cancel the press.
4833     *
4834     * Subclasses of View overriding this method should always call super.onFocusLost().
4835     *
4836     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4837     * @see #onWindowFocusChanged(boolean)
4838     *
4839     * @hide pending API council approval
4840     */
4841    protected void onFocusLost() {
4842        resetPressedState();
4843    }
4844
4845    private void resetPressedState() {
4846        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4847            return;
4848        }
4849
4850        if (isPressed()) {
4851            setPressed(false);
4852
4853            if (!mHasPerformedLongPress) {
4854                removeLongPressCallback();
4855            }
4856        }
4857    }
4858
4859    /**
4860     * Returns true if this view has focus
4861     *
4862     * @return True if this view has focus, false otherwise.
4863     */
4864    @ViewDebug.ExportedProperty(category = "focus")
4865    public boolean isFocused() {
4866        return (mPrivateFlags & FOCUSED) != 0;
4867    }
4868
4869    /**
4870     * Find the view in the hierarchy rooted at this view that currently has
4871     * focus.
4872     *
4873     * @return The view that currently has focus, or null if no focused view can
4874     *         be found.
4875     */
4876    public View findFocus() {
4877        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4878    }
4879
4880    /**
4881     * Indicates whether this view is one of the set of scrollable containers in
4882     * its window.
4883     *
4884     * @return whether this view is one of the set of scrollable containers in
4885     * its window
4886     *
4887     * @attr ref android.R.styleable#View_isScrollContainer
4888     */
4889    public boolean isScrollContainer() {
4890        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4891    }
4892
4893    /**
4894     * Change whether this view is one of the set of scrollable containers in
4895     * its window.  This will be used to determine whether the window can
4896     * resize or must pan when a soft input area is open -- scrollable
4897     * containers allow the window to use resize mode since the container
4898     * will appropriately shrink.
4899     *
4900     * @attr ref android.R.styleable#View_isScrollContainer
4901     */
4902    public void setScrollContainer(boolean isScrollContainer) {
4903        if (isScrollContainer) {
4904            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4905                mAttachInfo.mScrollContainers.add(this);
4906                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4907            }
4908            mPrivateFlags |= SCROLL_CONTAINER;
4909        } else {
4910            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4911                mAttachInfo.mScrollContainers.remove(this);
4912            }
4913            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4914        }
4915    }
4916
4917    /**
4918     * Returns the quality of the drawing cache.
4919     *
4920     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4921     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4922     *
4923     * @see #setDrawingCacheQuality(int)
4924     * @see #setDrawingCacheEnabled(boolean)
4925     * @see #isDrawingCacheEnabled()
4926     *
4927     * @attr ref android.R.styleable#View_drawingCacheQuality
4928     */
4929    public int getDrawingCacheQuality() {
4930        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4931    }
4932
4933    /**
4934     * Set the drawing cache quality of this view. This value is used only when the
4935     * drawing cache is enabled
4936     *
4937     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4938     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4939     *
4940     * @see #getDrawingCacheQuality()
4941     * @see #setDrawingCacheEnabled(boolean)
4942     * @see #isDrawingCacheEnabled()
4943     *
4944     * @attr ref android.R.styleable#View_drawingCacheQuality
4945     */
4946    public void setDrawingCacheQuality(int quality) {
4947        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4948    }
4949
4950    /**
4951     * Returns whether the screen should remain on, corresponding to the current
4952     * value of {@link #KEEP_SCREEN_ON}.
4953     *
4954     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4955     *
4956     * @see #setKeepScreenOn(boolean)
4957     *
4958     * @attr ref android.R.styleable#View_keepScreenOn
4959     */
4960    public boolean getKeepScreenOn() {
4961        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4962    }
4963
4964    /**
4965     * Controls whether the screen should remain on, modifying the
4966     * value of {@link #KEEP_SCREEN_ON}.
4967     *
4968     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4969     *
4970     * @see #getKeepScreenOn()
4971     *
4972     * @attr ref android.R.styleable#View_keepScreenOn
4973     */
4974    public void setKeepScreenOn(boolean keepScreenOn) {
4975        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4976    }
4977
4978    /**
4979     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4980     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4981     *
4982     * @attr ref android.R.styleable#View_nextFocusLeft
4983     */
4984    public int getNextFocusLeftId() {
4985        return mNextFocusLeftId;
4986    }
4987
4988    /**
4989     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4990     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4991     * decide automatically.
4992     *
4993     * @attr ref android.R.styleable#View_nextFocusLeft
4994     */
4995    public void setNextFocusLeftId(int nextFocusLeftId) {
4996        mNextFocusLeftId = nextFocusLeftId;
4997    }
4998
4999    /**
5000     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5001     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5002     *
5003     * @attr ref android.R.styleable#View_nextFocusRight
5004     */
5005    public int getNextFocusRightId() {
5006        return mNextFocusRightId;
5007    }
5008
5009    /**
5010     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5011     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5012     * decide automatically.
5013     *
5014     * @attr ref android.R.styleable#View_nextFocusRight
5015     */
5016    public void setNextFocusRightId(int nextFocusRightId) {
5017        mNextFocusRightId = nextFocusRightId;
5018    }
5019
5020    /**
5021     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5022     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5023     *
5024     * @attr ref android.R.styleable#View_nextFocusUp
5025     */
5026    public int getNextFocusUpId() {
5027        return mNextFocusUpId;
5028    }
5029
5030    /**
5031     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5032     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5033     * decide automatically.
5034     *
5035     * @attr ref android.R.styleable#View_nextFocusUp
5036     */
5037    public void setNextFocusUpId(int nextFocusUpId) {
5038        mNextFocusUpId = nextFocusUpId;
5039    }
5040
5041    /**
5042     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5043     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5044     *
5045     * @attr ref android.R.styleable#View_nextFocusDown
5046     */
5047    public int getNextFocusDownId() {
5048        return mNextFocusDownId;
5049    }
5050
5051    /**
5052     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5053     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5054     * decide automatically.
5055     *
5056     * @attr ref android.R.styleable#View_nextFocusDown
5057     */
5058    public void setNextFocusDownId(int nextFocusDownId) {
5059        mNextFocusDownId = nextFocusDownId;
5060    }
5061
5062    /**
5063     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5064     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5065     *
5066     * @attr ref android.R.styleable#View_nextFocusForward
5067     */
5068    public int getNextFocusForwardId() {
5069        return mNextFocusForwardId;
5070    }
5071
5072    /**
5073     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5074     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5075     * decide automatically.
5076     *
5077     * @attr ref android.R.styleable#View_nextFocusForward
5078     */
5079    public void setNextFocusForwardId(int nextFocusForwardId) {
5080        mNextFocusForwardId = nextFocusForwardId;
5081    }
5082
5083    /**
5084     * Returns the visibility of this view and all of its ancestors
5085     *
5086     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5087     */
5088    public boolean isShown() {
5089        View current = this;
5090        //noinspection ConstantConditions
5091        do {
5092            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5093                return false;
5094            }
5095            ViewParent parent = current.mParent;
5096            if (parent == null) {
5097                return false; // We are not attached to the view root
5098            }
5099            if (!(parent instanceof View)) {
5100                return true;
5101            }
5102            current = (View) parent;
5103        } while (current != null);
5104
5105        return false;
5106    }
5107
5108    /**
5109     * Called by the view hierarchy when the content insets for a window have
5110     * changed, to allow it to adjust its content to fit within those windows.
5111     * The content insets tell you the space that the status bar, input method,
5112     * and other system windows infringe on the application's window.
5113     *
5114     * <p>You do not normally need to deal with this function, since the default
5115     * window decoration given to applications takes care of applying it to the
5116     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5117     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5118     * and your content can be placed under those system elements.  You can then
5119     * use this method within your view hierarchy if you have parts of your UI
5120     * which you would like to ensure are not being covered.
5121     *
5122     * <p>The default implementation of this method simply applies the content
5123     * inset's to the view's padding.  This can be enabled through
5124     * {@link #setFitsSystemWindows(boolean)}.  Alternatively, you can override
5125     * the method and handle the insets however you would like.  Note that the
5126     * insets provided by the framework are always relative to the far edges
5127     * of the window, not accounting for the location of the called view within
5128     * that window.  (In fact when this method is called you do not yet know
5129     * where the layout will place the view, as it is done before layout happens.)
5130     *
5131     * <p>Note: unlike many View methods, there is no dispatch phase to this
5132     * call.  If you are overriding it in a ViewGroup and want to allow the
5133     * call to continue to your children, you must be sure to call the super
5134     * implementation.
5135     *
5136     * @param insets Current content insets of the window.  Prior to
5137     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5138     * the insets or else you and Android will be unhappy.
5139     *
5140     * @return Return true if this view applied the insets and it should not
5141     * continue propagating further down the hierarchy, false otherwise.
5142     */
5143    protected boolean fitSystemWindows(Rect insets) {
5144        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5145            mUserPaddingStart = -1;
5146            mUserPaddingEnd = -1;
5147            mUserPaddingRelative = false;
5148            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5149                    || mAttachInfo == null
5150                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5151                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5152                return true;
5153            } else {
5154                internalSetPadding(0, 0, 0, 0);
5155                return false;
5156            }
5157        }
5158        return false;
5159    }
5160
5161    /**
5162     * Set whether or not this view should account for system screen decorations
5163     * such as the status bar and inset its content. This allows this view to be
5164     * positioned in absolute screen coordinates and remain visible to the user.
5165     *
5166     * <p>This should only be used by top-level window decor views.
5167     *
5168     * @param fitSystemWindows true to inset content for system screen decorations, false for
5169     *                         default behavior.
5170     *
5171     * @attr ref android.R.styleable#View_fitsSystemWindows
5172     */
5173    public void setFitsSystemWindows(boolean fitSystemWindows) {
5174        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5175    }
5176
5177    /**
5178     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
5179     * will account for system screen decorations such as the status bar and inset its
5180     * content. This allows the view to be positioned in absolute screen coordinates
5181     * and remain visible to the user.
5182     *
5183     * @return true if this view will adjust its content bounds for system screen decorations.
5184     *
5185     * @attr ref android.R.styleable#View_fitsSystemWindows
5186     */
5187    public boolean fitsSystemWindows() {
5188        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5189    }
5190
5191    /**
5192     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5193     */
5194    public void requestFitSystemWindows() {
5195        if (mParent != null) {
5196            mParent.requestFitSystemWindows();
5197        }
5198    }
5199
5200    /**
5201     * For use by PhoneWindow to make its own system window fitting optional.
5202     * @hide
5203     */
5204    public void makeOptionalFitsSystemWindows() {
5205        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5206    }
5207
5208    /**
5209     * Returns the visibility status for this view.
5210     *
5211     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5212     * @attr ref android.R.styleable#View_visibility
5213     */
5214    @ViewDebug.ExportedProperty(mapping = {
5215        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5216        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5217        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5218    })
5219    public int getVisibility() {
5220        return mViewFlags & VISIBILITY_MASK;
5221    }
5222
5223    /**
5224     * Set the enabled state of this view.
5225     *
5226     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5227     * @attr ref android.R.styleable#View_visibility
5228     */
5229    @RemotableViewMethod
5230    public void setVisibility(int visibility) {
5231        setFlags(visibility, VISIBILITY_MASK);
5232        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5233    }
5234
5235    /**
5236     * Returns the enabled status for this view. The interpretation of the
5237     * enabled state varies by subclass.
5238     *
5239     * @return True if this view is enabled, false otherwise.
5240     */
5241    @ViewDebug.ExportedProperty
5242    public boolean isEnabled() {
5243        return (mViewFlags & ENABLED_MASK) == ENABLED;
5244    }
5245
5246    /**
5247     * Set the enabled state of this view. The interpretation of the enabled
5248     * state varies by subclass.
5249     *
5250     * @param enabled True if this view is enabled, false otherwise.
5251     */
5252    @RemotableViewMethod
5253    public void setEnabled(boolean enabled) {
5254        if (enabled == isEnabled()) return;
5255
5256        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5257
5258        /*
5259         * The View most likely has to change its appearance, so refresh
5260         * the drawable state.
5261         */
5262        refreshDrawableState();
5263
5264        // Invalidate too, since the default behavior for views is to be
5265        // be drawn at 50% alpha rather than to change the drawable.
5266        invalidate(true);
5267    }
5268
5269    /**
5270     * Set whether this view can receive the focus.
5271     *
5272     * Setting this to false will also ensure that this view is not focusable
5273     * in touch mode.
5274     *
5275     * @param focusable If true, this view can receive the focus.
5276     *
5277     * @see #setFocusableInTouchMode(boolean)
5278     * @attr ref android.R.styleable#View_focusable
5279     */
5280    public void setFocusable(boolean focusable) {
5281        if (!focusable) {
5282            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5283        }
5284        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5285    }
5286
5287    /**
5288     * Set whether this view can receive focus while in touch mode.
5289     *
5290     * Setting this to true will also ensure that this view is focusable.
5291     *
5292     * @param focusableInTouchMode If true, this view can receive the focus while
5293     *   in touch mode.
5294     *
5295     * @see #setFocusable(boolean)
5296     * @attr ref android.R.styleable#View_focusableInTouchMode
5297     */
5298    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5299        // Focusable in touch mode should always be set before the focusable flag
5300        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5301        // which, in touch mode, will not successfully request focus on this view
5302        // because the focusable in touch mode flag is not set
5303        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5304        if (focusableInTouchMode) {
5305            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5306        }
5307    }
5308
5309    /**
5310     * Set whether this view should have sound effects enabled for events such as
5311     * clicking and touching.
5312     *
5313     * <p>You may wish to disable sound effects for a view if you already play sounds,
5314     * for instance, a dial key that plays dtmf tones.
5315     *
5316     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5317     * @see #isSoundEffectsEnabled()
5318     * @see #playSoundEffect(int)
5319     * @attr ref android.R.styleable#View_soundEffectsEnabled
5320     */
5321    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5322        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5323    }
5324
5325    /**
5326     * @return whether this view should have sound effects enabled for events such as
5327     *     clicking and touching.
5328     *
5329     * @see #setSoundEffectsEnabled(boolean)
5330     * @see #playSoundEffect(int)
5331     * @attr ref android.R.styleable#View_soundEffectsEnabled
5332     */
5333    @ViewDebug.ExportedProperty
5334    public boolean isSoundEffectsEnabled() {
5335        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5336    }
5337
5338    /**
5339     * Set whether this view should have haptic feedback for events such as
5340     * long presses.
5341     *
5342     * <p>You may wish to disable haptic feedback if your view already controls
5343     * its own haptic feedback.
5344     *
5345     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5346     * @see #isHapticFeedbackEnabled()
5347     * @see #performHapticFeedback(int)
5348     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5349     */
5350    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5351        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5352    }
5353
5354    /**
5355     * @return whether this view should have haptic feedback enabled for events
5356     * long presses.
5357     *
5358     * @see #setHapticFeedbackEnabled(boolean)
5359     * @see #performHapticFeedback(int)
5360     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5361     */
5362    @ViewDebug.ExportedProperty
5363    public boolean isHapticFeedbackEnabled() {
5364        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5365    }
5366
5367    /**
5368     * Returns the layout direction for this view.
5369     *
5370     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5371     *   {@link #LAYOUT_DIRECTION_RTL},
5372     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5373     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5374     * @attr ref android.R.styleable#View_layoutDirection
5375     */
5376    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5377        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5378        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5379        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5380        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5381    })
5382    public int getLayoutDirection() {
5383        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5384    }
5385
5386    /**
5387     * Set the layout direction for this view. This will propagate a reset of layout direction
5388     * resolution to the view's children and resolve layout direction for this view.
5389     *
5390     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5391     *   {@link #LAYOUT_DIRECTION_RTL},
5392     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5393     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5394     *
5395     * @attr ref android.R.styleable#View_layoutDirection
5396     */
5397    @RemotableViewMethod
5398    public void setLayoutDirection(int layoutDirection) {
5399        if (getLayoutDirection() != layoutDirection) {
5400            // Reset the current layout direction and the resolved one
5401            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5402            resetResolvedLayoutDirection();
5403            // Set the new layout direction (filtered) and ask for a layout pass
5404            mPrivateFlags2 |=
5405                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5406            requestLayout();
5407        }
5408    }
5409
5410    /**
5411     * Returns the resolved layout direction for this view.
5412     *
5413     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5414     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5415     */
5416    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5417        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5418        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5419    })
5420    public int getResolvedLayoutDirection() {
5421        // The layout diretion will be resolved only if needed
5422        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5423            resolveLayoutDirection();
5424        }
5425        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5426                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5427    }
5428
5429    /**
5430     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5431     * layout attribute and/or the inherited value from the parent
5432     *
5433     * @return true if the layout is right-to-left.
5434     */
5435    @ViewDebug.ExportedProperty(category = "layout")
5436    public boolean isLayoutRtl() {
5437        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5438    }
5439
5440    /**
5441     * Indicates whether the view is currently tracking transient state that the
5442     * app should not need to concern itself with saving and restoring, but that
5443     * the framework should take special note to preserve when possible.
5444     *
5445     * <p>A view with transient state cannot be trivially rebound from an external
5446     * data source, such as an adapter binding item views in a list. This may be
5447     * because the view is performing an animation, tracking user selection
5448     * of content, or similar.</p>
5449     *
5450     * @return true if the view has transient state
5451     */
5452    @ViewDebug.ExportedProperty(category = "layout")
5453    public boolean hasTransientState() {
5454        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5455    }
5456
5457    /**
5458     * Set whether this view is currently tracking transient state that the
5459     * framework should attempt to preserve when possible. This flag is reference counted,
5460     * so every call to setHasTransientState(true) should be paired with a later call
5461     * to setHasTransientState(false).
5462     *
5463     * <p>A view with transient state cannot be trivially rebound from an external
5464     * data source, such as an adapter binding item views in a list. This may be
5465     * because the view is performing an animation, tracking user selection
5466     * of content, or similar.</p>
5467     *
5468     * @param hasTransientState true if this view has transient state
5469     */
5470    public void setHasTransientState(boolean hasTransientState) {
5471        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5472                mTransientStateCount - 1;
5473        if (mTransientStateCount < 0) {
5474            mTransientStateCount = 0;
5475            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5476                    "unmatched pair of setHasTransientState calls");
5477        }
5478        if ((hasTransientState && mTransientStateCount == 1) ||
5479                (hasTransientState && mTransientStateCount == 0)) {
5480            // update flag if we've just incremented up from 0 or decremented down to 0
5481            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5482                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5483            if (mParent != null) {
5484                try {
5485                    mParent.childHasTransientStateChanged(this, hasTransientState);
5486                } catch (AbstractMethodError e) {
5487                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5488                            " does not fully implement ViewParent", e);
5489                }
5490            }
5491        }
5492    }
5493
5494    /**
5495     * If this view doesn't do any drawing on its own, set this flag to
5496     * allow further optimizations. By default, this flag is not set on
5497     * View, but could be set on some View subclasses such as ViewGroup.
5498     *
5499     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5500     * you should clear this flag.
5501     *
5502     * @param willNotDraw whether or not this View draw on its own
5503     */
5504    public void setWillNotDraw(boolean willNotDraw) {
5505        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5506    }
5507
5508    /**
5509     * Returns whether or not this View draws on its own.
5510     *
5511     * @return true if this view has nothing to draw, false otherwise
5512     */
5513    @ViewDebug.ExportedProperty(category = "drawing")
5514    public boolean willNotDraw() {
5515        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5516    }
5517
5518    /**
5519     * When a View's drawing cache is enabled, drawing is redirected to an
5520     * offscreen bitmap. Some views, like an ImageView, must be able to
5521     * bypass this mechanism if they already draw a single bitmap, to avoid
5522     * unnecessary usage of the memory.
5523     *
5524     * @param willNotCacheDrawing true if this view does not cache its
5525     *        drawing, false otherwise
5526     */
5527    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5528        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5529    }
5530
5531    /**
5532     * Returns whether or not this View can cache its drawing or not.
5533     *
5534     * @return true if this view does not cache its drawing, false otherwise
5535     */
5536    @ViewDebug.ExportedProperty(category = "drawing")
5537    public boolean willNotCacheDrawing() {
5538        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5539    }
5540
5541    /**
5542     * Indicates whether this view reacts to click events or not.
5543     *
5544     * @return true if the view is clickable, false otherwise
5545     *
5546     * @see #setClickable(boolean)
5547     * @attr ref android.R.styleable#View_clickable
5548     */
5549    @ViewDebug.ExportedProperty
5550    public boolean isClickable() {
5551        return (mViewFlags & CLICKABLE) == CLICKABLE;
5552    }
5553
5554    /**
5555     * Enables or disables click events for this view. When a view
5556     * is clickable it will change its state to "pressed" on every click.
5557     * Subclasses should set the view clickable to visually react to
5558     * user's clicks.
5559     *
5560     * @param clickable true to make the view clickable, false otherwise
5561     *
5562     * @see #isClickable()
5563     * @attr ref android.R.styleable#View_clickable
5564     */
5565    public void setClickable(boolean clickable) {
5566        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5567    }
5568
5569    /**
5570     * Indicates whether this view reacts to long click events or not.
5571     *
5572     * @return true if the view is long clickable, false otherwise
5573     *
5574     * @see #setLongClickable(boolean)
5575     * @attr ref android.R.styleable#View_longClickable
5576     */
5577    public boolean isLongClickable() {
5578        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5579    }
5580
5581    /**
5582     * Enables or disables long click events for this view. When a view is long
5583     * clickable it reacts to the user holding down the button for a longer
5584     * duration than a tap. This event can either launch the listener or a
5585     * context menu.
5586     *
5587     * @param longClickable true to make the view long clickable, false otherwise
5588     * @see #isLongClickable()
5589     * @attr ref android.R.styleable#View_longClickable
5590     */
5591    public void setLongClickable(boolean longClickable) {
5592        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5593    }
5594
5595    /**
5596     * Sets the pressed state for this view.
5597     *
5598     * @see #isClickable()
5599     * @see #setClickable(boolean)
5600     *
5601     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5602     *        the View's internal state from a previously set "pressed" state.
5603     */
5604    public void setPressed(boolean pressed) {
5605        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5606
5607        if (pressed) {
5608            mPrivateFlags |= PRESSED;
5609        } else {
5610            mPrivateFlags &= ~PRESSED;
5611        }
5612
5613        if (needsRefresh) {
5614            refreshDrawableState();
5615        }
5616        dispatchSetPressed(pressed);
5617    }
5618
5619    /**
5620     * Dispatch setPressed to all of this View's children.
5621     *
5622     * @see #setPressed(boolean)
5623     *
5624     * @param pressed The new pressed state
5625     */
5626    protected void dispatchSetPressed(boolean pressed) {
5627    }
5628
5629    /**
5630     * Indicates whether the view is currently in pressed state. Unless
5631     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5632     * the pressed state.
5633     *
5634     * @see #setPressed(boolean)
5635     * @see #isClickable()
5636     * @see #setClickable(boolean)
5637     *
5638     * @return true if the view is currently pressed, false otherwise
5639     */
5640    public boolean isPressed() {
5641        return (mPrivateFlags & PRESSED) == PRESSED;
5642    }
5643
5644    /**
5645     * Indicates whether this view will save its state (that is,
5646     * whether its {@link #onSaveInstanceState} method will be called).
5647     *
5648     * @return Returns true if the view state saving is enabled, else false.
5649     *
5650     * @see #setSaveEnabled(boolean)
5651     * @attr ref android.R.styleable#View_saveEnabled
5652     */
5653    public boolean isSaveEnabled() {
5654        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5655    }
5656
5657    /**
5658     * Controls whether the saving of this view's state is
5659     * enabled (that is, whether its {@link #onSaveInstanceState} method
5660     * will be called).  Note that even if freezing is enabled, the
5661     * view still must have an id assigned to it (via {@link #setId(int)})
5662     * for its state to be saved.  This flag can only disable the
5663     * saving of this view; any child views may still have their state saved.
5664     *
5665     * @param enabled Set to false to <em>disable</em> state saving, or true
5666     * (the default) to allow it.
5667     *
5668     * @see #isSaveEnabled()
5669     * @see #setId(int)
5670     * @see #onSaveInstanceState()
5671     * @attr ref android.R.styleable#View_saveEnabled
5672     */
5673    public void setSaveEnabled(boolean enabled) {
5674        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5675    }
5676
5677    /**
5678     * Gets whether the framework should discard touches when the view's
5679     * window is obscured by another visible window.
5680     * Refer to the {@link View} security documentation for more details.
5681     *
5682     * @return True if touch filtering is enabled.
5683     *
5684     * @see #setFilterTouchesWhenObscured(boolean)
5685     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5686     */
5687    @ViewDebug.ExportedProperty
5688    public boolean getFilterTouchesWhenObscured() {
5689        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5690    }
5691
5692    /**
5693     * Sets whether the framework should discard touches when the view's
5694     * window is obscured by another visible window.
5695     * Refer to the {@link View} security documentation for more details.
5696     *
5697     * @param enabled True if touch filtering should be enabled.
5698     *
5699     * @see #getFilterTouchesWhenObscured
5700     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5701     */
5702    public void setFilterTouchesWhenObscured(boolean enabled) {
5703        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5704                FILTER_TOUCHES_WHEN_OBSCURED);
5705    }
5706
5707    /**
5708     * Indicates whether the entire hierarchy under this view will save its
5709     * state when a state saving traversal occurs from its parent.  The default
5710     * is true; if false, these views will not be saved unless
5711     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5712     *
5713     * @return Returns true if the view state saving from parent is enabled, else false.
5714     *
5715     * @see #setSaveFromParentEnabled(boolean)
5716     */
5717    public boolean isSaveFromParentEnabled() {
5718        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5719    }
5720
5721    /**
5722     * Controls whether the entire hierarchy under this view will save its
5723     * state when a state saving traversal occurs from its parent.  The default
5724     * is true; if false, these views will not be saved unless
5725     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5726     *
5727     * @param enabled Set to false to <em>disable</em> state saving, or true
5728     * (the default) to allow it.
5729     *
5730     * @see #isSaveFromParentEnabled()
5731     * @see #setId(int)
5732     * @see #onSaveInstanceState()
5733     */
5734    public void setSaveFromParentEnabled(boolean enabled) {
5735        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5736    }
5737
5738
5739    /**
5740     * Returns whether this View is able to take focus.
5741     *
5742     * @return True if this view can take focus, or false otherwise.
5743     * @attr ref android.R.styleable#View_focusable
5744     */
5745    @ViewDebug.ExportedProperty(category = "focus")
5746    public final boolean isFocusable() {
5747        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5748    }
5749
5750    /**
5751     * When a view is focusable, it may not want to take focus when in touch mode.
5752     * For example, a button would like focus when the user is navigating via a D-pad
5753     * so that the user can click on it, but once the user starts touching the screen,
5754     * the button shouldn't take focus
5755     * @return Whether the view is focusable in touch mode.
5756     * @attr ref android.R.styleable#View_focusableInTouchMode
5757     */
5758    @ViewDebug.ExportedProperty
5759    public final boolean isFocusableInTouchMode() {
5760        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5761    }
5762
5763    /**
5764     * Find the nearest view in the specified direction that can take focus.
5765     * This does not actually give focus to that view.
5766     *
5767     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5768     *
5769     * @return The nearest focusable in the specified direction, or null if none
5770     *         can be found.
5771     */
5772    public View focusSearch(int direction) {
5773        if (mParent != null) {
5774            return mParent.focusSearch(this, direction);
5775        } else {
5776            return null;
5777        }
5778    }
5779
5780    /**
5781     * This method is the last chance for the focused view and its ancestors to
5782     * respond to an arrow key. This is called when the focused view did not
5783     * consume the key internally, nor could the view system find a new view in
5784     * the requested direction to give focus to.
5785     *
5786     * @param focused The currently focused view.
5787     * @param direction The direction focus wants to move. One of FOCUS_UP,
5788     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5789     * @return True if the this view consumed this unhandled move.
5790     */
5791    public boolean dispatchUnhandledMove(View focused, int direction) {
5792        return false;
5793    }
5794
5795    /**
5796     * If a user manually specified the next view id for a particular direction,
5797     * use the root to look up the view.
5798     * @param root The root view of the hierarchy containing this view.
5799     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5800     * or FOCUS_BACKWARD.
5801     * @return The user specified next view, or null if there is none.
5802     */
5803    View findUserSetNextFocus(View root, int direction) {
5804        switch (direction) {
5805            case FOCUS_LEFT:
5806                if (mNextFocusLeftId == View.NO_ID) return null;
5807                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5808            case FOCUS_RIGHT:
5809                if (mNextFocusRightId == View.NO_ID) return null;
5810                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5811            case FOCUS_UP:
5812                if (mNextFocusUpId == View.NO_ID) return null;
5813                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5814            case FOCUS_DOWN:
5815                if (mNextFocusDownId == View.NO_ID) return null;
5816                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5817            case FOCUS_FORWARD:
5818                if (mNextFocusForwardId == View.NO_ID) return null;
5819                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5820            case FOCUS_BACKWARD: {
5821                if (mID == View.NO_ID) return null;
5822                final int id = mID;
5823                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5824                    @Override
5825                    public boolean apply(View t) {
5826                        return t.mNextFocusForwardId == id;
5827                    }
5828                });
5829            }
5830        }
5831        return null;
5832    }
5833
5834    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5835        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5836            @Override
5837            public boolean apply(View t) {
5838                return t.mID == childViewId;
5839            }
5840        });
5841
5842        if (result == null) {
5843            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5844                    + "by user for id " + childViewId);
5845        }
5846        return result;
5847    }
5848
5849    /**
5850     * Find and return all focusable views that are descendants of this view,
5851     * possibly including this view if it is focusable itself.
5852     *
5853     * @param direction The direction of the focus
5854     * @return A list of focusable views
5855     */
5856    public ArrayList<View> getFocusables(int direction) {
5857        ArrayList<View> result = new ArrayList<View>(24);
5858        addFocusables(result, direction);
5859        return result;
5860    }
5861
5862    /**
5863     * Add any focusable views that are descendants of this view (possibly
5864     * including this view if it is focusable itself) to views.  If we are in touch mode,
5865     * only add views that are also focusable in touch mode.
5866     *
5867     * @param views Focusable views found so far
5868     * @param direction The direction of the focus
5869     */
5870    public void addFocusables(ArrayList<View> views, int direction) {
5871        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5872    }
5873
5874    /**
5875     * Adds any focusable views that are descendants of this view (possibly
5876     * including this view if it is focusable itself) to views. This method
5877     * adds all focusable views regardless if we are in touch mode or
5878     * only views focusable in touch mode if we are in touch mode or
5879     * only views that can take accessibility focus if accessibility is enabeld
5880     * depending on the focusable mode paramater.
5881     *
5882     * @param views Focusable views found so far or null if all we are interested is
5883     *        the number of focusables.
5884     * @param direction The direction of the focus.
5885     * @param focusableMode The type of focusables to be added.
5886     *
5887     * @see #FOCUSABLES_ALL
5888     * @see #FOCUSABLES_TOUCH_MODE
5889     */
5890    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5891        if (views == null) {
5892            return;
5893        }
5894        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
5895            if (AccessibilityManager.getInstance(mContext).isEnabled()
5896                    && includeForAccessibility()) {
5897                views.add(this);
5898                return;
5899            }
5900        }
5901        if (!isFocusable()) {
5902            return;
5903        }
5904        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
5905                && isInTouchMode() && !isFocusableInTouchMode()) {
5906            return;
5907        }
5908        views.add(this);
5909    }
5910
5911    /**
5912     * Finds the Views that contain given text. The containment is case insensitive.
5913     * The search is performed by either the text that the View renders or the content
5914     * description that describes the view for accessibility purposes and the view does
5915     * not render or both. Clients can specify how the search is to be performed via
5916     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5917     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5918     *
5919     * @param outViews The output list of matching Views.
5920     * @param searched The text to match against.
5921     *
5922     * @see #FIND_VIEWS_WITH_TEXT
5923     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5924     * @see #setContentDescription(CharSequence)
5925     */
5926    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5927        if (getAccessibilityNodeProvider() != null) {
5928            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5929                outViews.add(this);
5930            }
5931        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5932                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5933            String searchedLowerCase = searched.toString().toLowerCase();
5934            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5935            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5936                outViews.add(this);
5937            }
5938        }
5939    }
5940
5941    /**
5942     * Find and return all touchable views that are descendants of this view,
5943     * possibly including this view if it is touchable itself.
5944     *
5945     * @return A list of touchable views
5946     */
5947    public ArrayList<View> getTouchables() {
5948        ArrayList<View> result = new ArrayList<View>();
5949        addTouchables(result);
5950        return result;
5951    }
5952
5953    /**
5954     * Add any touchable views that are descendants of this view (possibly
5955     * including this view if it is touchable itself) to views.
5956     *
5957     * @param views Touchable views found so far
5958     */
5959    public void addTouchables(ArrayList<View> views) {
5960        final int viewFlags = mViewFlags;
5961
5962        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5963                && (viewFlags & ENABLED_MASK) == ENABLED) {
5964            views.add(this);
5965        }
5966    }
5967
5968    /**
5969     * Returns whether this View is accessibility focused.
5970     *
5971     * @return True if this View is accessibility focused.
5972     */
5973    boolean isAccessibilityFocused() {
5974        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
5975    }
5976
5977    /**
5978     * Call this to try to give accessibility focus to this view.
5979     *
5980     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
5981     * returns false or the view is no visible or the view already has accessibility
5982     * focus.
5983     *
5984     * See also {@link #focusSearch(int)}, which is what you call to say that you
5985     * have focus, and you want your parent to look for the next one.
5986     *
5987     * @return Whether this view actually took accessibility focus.
5988     *
5989     * @hide
5990     */
5991    public boolean requestAccessibilityFocus() {
5992        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
5993        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
5994            return false;
5995        }
5996        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5997            return false;
5998        }
5999        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6000            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6001            ViewRootImpl viewRootImpl = getViewRootImpl();
6002            if (viewRootImpl != null) {
6003                viewRootImpl.setAccessibilityFocusedHost(this);
6004            }
6005            invalidate();
6006            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6007            notifyAccessibilityStateChanged();
6008            // Try to give input focus to this view - not a descendant.
6009            requestFocusNoSearch(View.FOCUS_DOWN, null);
6010            return true;
6011        }
6012        return false;
6013    }
6014
6015    /**
6016     * Call this to try to clear accessibility focus of this view.
6017     *
6018     * See also {@link #focusSearch(int)}, which is what you call to say that you
6019     * have focus, and you want your parent to look for the next one.
6020     *
6021     * @hide
6022     */
6023    public void clearAccessibilityFocus() {
6024        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6025            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6026            ViewRootImpl viewRootImpl = getViewRootImpl();
6027            if (viewRootImpl != null) {
6028                viewRootImpl.setAccessibilityFocusedHost(null);
6029            }
6030            invalidate();
6031            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6032            notifyAccessibilityStateChanged();
6033            // Try to move accessibility focus to the input focus.
6034            View rootView = getRootView();
6035            if (rootView != null) {
6036                View inputFocus = rootView.findFocus();
6037                if (inputFocus != null) {
6038                    inputFocus.requestAccessibilityFocus();
6039                }
6040            }
6041        }
6042    }
6043
6044    /**
6045     * Find the best view to take accessibility focus from a hover.
6046     * This function finds the deepest actionable view and if that
6047     * fails ask the parent to take accessibility focus from hover.
6048     *
6049     * @param x The X hovered location in this view coorditantes.
6050     * @param y The Y hovered location in this view coorditantes.
6051     * @return Whether the request was handled.
6052     *
6053     * @hide
6054     */
6055    public boolean requestAccessibilityFocusFromHover(float x, float y) {
6056        if (onRequestAccessibilityFocusFromHover(x, y)) {
6057            return true;
6058        }
6059        ViewParent parent = mParent;
6060        if (parent instanceof View) {
6061            View parentView = (View) parent;
6062
6063            float[] position = mAttachInfo.mTmpTransformLocation;
6064            position[0] = x;
6065            position[1] = y;
6066
6067            // Compensate for the transformation of the current matrix.
6068            if (!hasIdentityMatrix()) {
6069                getMatrix().mapPoints(position);
6070            }
6071
6072            // Compensate for the parent scroll and the offset
6073            // of this view stop from the parent top.
6074            position[0] += mLeft - parentView.mScrollX;
6075            position[1] += mTop - parentView.mScrollY;
6076
6077            return parentView.requestAccessibilityFocusFromHover(position[0], position[1]);
6078        }
6079        return false;
6080    }
6081
6082    /**
6083     * Requests to give this View focus from hover.
6084     *
6085     * @param x The X hovered location in this view coorditantes.
6086     * @param y The Y hovered location in this view coorditantes.
6087     * @return Whether the request was handled.
6088     *
6089     * @hide
6090     */
6091    public boolean onRequestAccessibilityFocusFromHover(float x, float y) {
6092        if (includeForAccessibility()
6093                && (isActionableForAccessibility() || hasListenersForAccessibility())) {
6094            return requestAccessibilityFocus();
6095        }
6096        return false;
6097    }
6098
6099    /**
6100     * Clears accessibility focus without calling any callback methods
6101     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6102     * is used for clearing accessibility focus when giving this focus to
6103     * another view.
6104     */
6105    void clearAccessibilityFocusNoCallbacks() {
6106        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6107            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6108            invalidate();
6109        }
6110    }
6111
6112    /**
6113     * Call this to try to give focus to a specific view or to one of its
6114     * descendants.
6115     *
6116     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6117     * false), or if it is focusable and it is not focusable in touch mode
6118     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6119     *
6120     * See also {@link #focusSearch(int)}, which is what you call to say that you
6121     * have focus, and you want your parent to look for the next one.
6122     *
6123     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6124     * {@link #FOCUS_DOWN} and <code>null</code>.
6125     *
6126     * @return Whether this view or one of its descendants actually took focus.
6127     */
6128    public final boolean requestFocus() {
6129        return requestFocus(View.FOCUS_DOWN);
6130    }
6131
6132    /**
6133     * Call this to try to give focus to a specific view or to one of its
6134     * descendants and give it a hint about what direction focus is heading.
6135     *
6136     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6137     * false), or if it is focusable and it is not focusable in touch mode
6138     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6139     *
6140     * See also {@link #focusSearch(int)}, which is what you call to say that you
6141     * have focus, and you want your parent to look for the next one.
6142     *
6143     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6144     * <code>null</code> set for the previously focused rectangle.
6145     *
6146     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6147     * @return Whether this view or one of its descendants actually took focus.
6148     */
6149    public final boolean requestFocus(int direction) {
6150        return requestFocus(direction, null);
6151    }
6152
6153    /**
6154     * Call this to try to give focus to a specific view or to one of its descendants
6155     * and give it hints about the direction and a specific rectangle that the focus
6156     * is coming from.  The rectangle can help give larger views a finer grained hint
6157     * about where focus is coming from, and therefore, where to show selection, or
6158     * forward focus change internally.
6159     *
6160     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6161     * false), or if it is focusable and it is not focusable in touch mode
6162     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6163     *
6164     * A View will not take focus if it is not visible.
6165     *
6166     * A View will not take focus if one of its parents has
6167     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6168     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6169     *
6170     * See also {@link #focusSearch(int)}, which is what you call to say that you
6171     * have focus, and you want your parent to look for the next one.
6172     *
6173     * You may wish to override this method if your custom {@link View} has an internal
6174     * {@link View} that it wishes to forward the request to.
6175     *
6176     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6177     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6178     *        to give a finer grained hint about where focus is coming from.  May be null
6179     *        if there is no hint.
6180     * @return Whether this view or one of its descendants actually took focus.
6181     */
6182    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6183        return requestFocusNoSearch(direction, previouslyFocusedRect);
6184    }
6185
6186    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6187        // need to be focusable
6188        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6189                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6190            return false;
6191        }
6192
6193        // need to be focusable in touch mode if in touch mode
6194        if (isInTouchMode() &&
6195            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6196               return false;
6197        }
6198
6199        // need to not have any parents blocking us
6200        if (hasAncestorThatBlocksDescendantFocus()) {
6201            return false;
6202        }
6203
6204        handleFocusGainInternal(direction, previouslyFocusedRect);
6205        return true;
6206    }
6207
6208    /**
6209     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6210     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6211     * touch mode to request focus when they are touched.
6212     *
6213     * @return Whether this view or one of its descendants actually took focus.
6214     *
6215     * @see #isInTouchMode()
6216     *
6217     */
6218    public final boolean requestFocusFromTouch() {
6219        // Leave touch mode if we need to
6220        if (isInTouchMode()) {
6221            ViewRootImpl viewRoot = getViewRootImpl();
6222            if (viewRoot != null) {
6223                viewRoot.ensureTouchMode(false);
6224            }
6225        }
6226        return requestFocus(View.FOCUS_DOWN);
6227    }
6228
6229    /**
6230     * @return Whether any ancestor of this view blocks descendant focus.
6231     */
6232    private boolean hasAncestorThatBlocksDescendantFocus() {
6233        ViewParent ancestor = mParent;
6234        while (ancestor instanceof ViewGroup) {
6235            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6236            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6237                return true;
6238            } else {
6239                ancestor = vgAncestor.getParent();
6240            }
6241        }
6242        return false;
6243    }
6244
6245    /**
6246     * Gets the mode for determining whether this View is important for accessibility
6247     * which is if it fires accessibility events and if it is reported to
6248     * accessibility services that query the screen.
6249     *
6250     * @return The mode for determining whether a View is important for accessibility.
6251     *
6252     * @attr ref android.R.styleable#View_importantForAccessibility
6253     *
6254     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6255     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6256     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6257     */
6258    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6259            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO,
6260                    to = "IMPORTANT_FOR_ACCESSIBILITY_AUTO"),
6261            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES,
6262                    to = "IMPORTANT_FOR_ACCESSIBILITY_YES"),
6263            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO,
6264                    to = "IMPORTANT_FOR_ACCESSIBILITY_NO")
6265        })
6266    public int getImportantForAccessibility() {
6267        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6268                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6269    }
6270
6271    /**
6272     * Sets how to determine whether this view is important for accessibility
6273     * which is if it fires accessibility events and if it is reported to
6274     * accessibility services that query the screen.
6275     *
6276     * @param mode How to determine whether this view is important for accessibility.
6277     *
6278     * @attr ref android.R.styleable#View_importantForAccessibility
6279     *
6280     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6281     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6282     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6283     */
6284    public void setImportantForAccessibility(int mode) {
6285        if (mode != getImportantForAccessibility()) {
6286            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6287            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6288                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6289            notifyAccessibilityStateChanged();
6290        }
6291    }
6292
6293    /**
6294     * Gets whether this view should be exposed for accessibility.
6295     *
6296     * @return Whether the view is exposed for accessibility.
6297     *
6298     * @hide
6299     */
6300    public boolean isImportantForAccessibility() {
6301        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6302                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6303        switch (mode) {
6304            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6305                return true;
6306            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6307                return false;
6308            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6309                return isActionableForAccessibility() || hasListenersForAccessibility();
6310            default:
6311                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6312                        + mode);
6313        }
6314    }
6315
6316    /**
6317     * Gets the parent for accessibility purposes. Note that the parent for
6318     * accessibility is not necessary the immediate parent. It is the first
6319     * predecessor that is important for accessibility.
6320     *
6321     * @return The parent for accessibility purposes.
6322     */
6323    public ViewParent getParentForAccessibility() {
6324        if (mParent instanceof View) {
6325            View parentView = (View) mParent;
6326            if (parentView.includeForAccessibility()) {
6327                return mParent;
6328            } else {
6329                return mParent.getParentForAccessibility();
6330            }
6331        }
6332        return null;
6333    }
6334
6335    /**
6336     * Adds the children of a given View for accessibility. Since some Views are
6337     * not important for accessibility the children for accessibility are not
6338     * necessarily direct children of the riew, rather they are the first level of
6339     * descendants important for accessibility.
6340     *
6341     * @param children The list of children for accessibility.
6342     */
6343    public void addChildrenForAccessibility(ArrayList<View> children) {
6344        if (includeForAccessibility()) {
6345            children.add(this);
6346        }
6347    }
6348
6349    /**
6350     * Whether to regard this view for accessibility. A view is regarded for
6351     * accessibility if it is important for accessibility or the querying
6352     * accessibility service has explicitly requested that view not
6353     * important for accessibility are regarded.
6354     *
6355     * @return Whether to regard the view for accessibility.
6356     */
6357    boolean includeForAccessibility() {
6358        if (mAttachInfo != null) {
6359            if (!mAttachInfo.mIncludeNotImportantViews) {
6360                return isImportantForAccessibility() && isDisplayedOnScreen();
6361            } else {
6362                return isDisplayedOnScreen();
6363            }
6364        }
6365        return false;
6366    }
6367
6368    /**
6369     * Returns whether the View is considered actionable from
6370     * accessibility perspective. Such view are important for
6371     * accessiiblity.
6372     *
6373     * @return True if the view is actionable for accessibility.
6374     */
6375    private boolean isActionableForAccessibility() {
6376        return (isClickable() || isLongClickable() || isFocusable());
6377    }
6378
6379    /**
6380     * Returns whether the View has registered callbacks wich makes it
6381     * important for accessiiblity.
6382     *
6383     * @return True if the view is actionable for accessibility.
6384     */
6385    private boolean hasListenersForAccessibility() {
6386        ListenerInfo info = getListenerInfo();
6387        return mTouchDelegate != null || info.mOnKeyListener != null
6388                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6389                || info.mOnHoverListener != null || info.mOnDragListener != null;
6390    }
6391
6392    /**
6393     * Notifies accessibility services that some view's important for
6394     * accessibility state has changed. Note that such notifications
6395     * are made at most once every
6396     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6397     * to avoid unnecessary load to the system. Also once a view has
6398     * made a notifucation this method is a NOP until the notification has
6399     * been sent to clients.
6400     *
6401     * @hide
6402     *
6403     * TODO: Makse sure this method is called for any view state change
6404     *       that is interesting for accessilility purposes.
6405     */
6406    public void notifyAccessibilityStateChanged() {
6407        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6408            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6409            if (mParent != null) {
6410                mParent.childAccessibilityStateChanged(this);
6411            }
6412        }
6413    }
6414
6415    /**
6416     * Reset the state indicating the this view has requested clients
6417     * interested in its accessiblity state to be notified.
6418     *
6419     * @hide
6420     */
6421    public void resetAccessibilityStateChanged() {
6422        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6423    }
6424
6425    /**
6426     * Performs the specified accessibility action on the view. For
6427     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6428     *
6429     * @param action The action to perform.
6430     * @return Whether the action was performed.
6431     */
6432    public boolean performAccessibilityAction(int action, Bundle args) {
6433        switch (action) {
6434            case AccessibilityNodeInfo.ACTION_CLICK: {
6435                if (isClickable()) {
6436                    performClick();
6437                }
6438            } break;
6439            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6440                if (isLongClickable()) {
6441                    performLongClick();
6442                }
6443            } break;
6444            case AccessibilityNodeInfo.ACTION_FOCUS: {
6445                if (!hasFocus()) {
6446                    // Get out of touch mode since accessibility
6447                    // wants to move focus around.
6448                    getViewRootImpl().ensureTouchMode(false);
6449                    return requestFocus();
6450                }
6451            } break;
6452            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6453                if (hasFocus()) {
6454                    clearFocus();
6455                    return !isFocused();
6456                }
6457            } break;
6458            case AccessibilityNodeInfo.ACTION_SELECT: {
6459                if (!isSelected()) {
6460                    setSelected(true);
6461                    return isSelected();
6462                }
6463            } break;
6464            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6465                if (isSelected()) {
6466                    setSelected(false);
6467                    return !isSelected();
6468                }
6469            } break;
6470            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6471                if (!isAccessibilityFocused()) {
6472                    return requestAccessibilityFocus();
6473                }
6474            } break;
6475            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6476                if (isAccessibilityFocused()) {
6477                    clearAccessibilityFocus();
6478                    return true;
6479                }
6480            } break;
6481        }
6482        return false;
6483    }
6484
6485    /**
6486     * @hide
6487     */
6488    public void dispatchStartTemporaryDetach() {
6489        onStartTemporaryDetach();
6490    }
6491
6492    /**
6493     * This is called when a container is going to temporarily detach a child, with
6494     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6495     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6496     * {@link #onDetachedFromWindow()} when the container is done.
6497     */
6498    public void onStartTemporaryDetach() {
6499        removeUnsetPressCallback();
6500        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6501    }
6502
6503    /**
6504     * @hide
6505     */
6506    public void dispatchFinishTemporaryDetach() {
6507        onFinishTemporaryDetach();
6508    }
6509
6510    /**
6511     * Called after {@link #onStartTemporaryDetach} when the container is done
6512     * changing the view.
6513     */
6514    public void onFinishTemporaryDetach() {
6515    }
6516
6517    /**
6518     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6519     * for this view's window.  Returns null if the view is not currently attached
6520     * to the window.  Normally you will not need to use this directly, but
6521     * just use the standard high-level event callbacks like
6522     * {@link #onKeyDown(int, KeyEvent)}.
6523     */
6524    public KeyEvent.DispatcherState getKeyDispatcherState() {
6525        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6526    }
6527
6528    /**
6529     * Dispatch a key event before it is processed by any input method
6530     * associated with the view hierarchy.  This can be used to intercept
6531     * key events in special situations before the IME consumes them; a
6532     * typical example would be handling the BACK key to update the application's
6533     * UI instead of allowing the IME to see it and close itself.
6534     *
6535     * @param event The key event to be dispatched.
6536     * @return True if the event was handled, false otherwise.
6537     */
6538    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6539        return onKeyPreIme(event.getKeyCode(), event);
6540    }
6541
6542    /**
6543     * Dispatch a key event to the next view on the focus path. This path runs
6544     * from the top of the view tree down to the currently focused view. If this
6545     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6546     * the next node down the focus path. This method also fires any key
6547     * listeners.
6548     *
6549     * @param event The key event to be dispatched.
6550     * @return True if the event was handled, false otherwise.
6551     */
6552    public boolean dispatchKeyEvent(KeyEvent event) {
6553        if (mInputEventConsistencyVerifier != null) {
6554            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6555        }
6556
6557        // Give any attached key listener a first crack at the event.
6558        //noinspection SimplifiableIfStatement
6559        ListenerInfo li = mListenerInfo;
6560        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6561                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6562            return true;
6563        }
6564
6565        if (event.dispatch(this, mAttachInfo != null
6566                ? mAttachInfo.mKeyDispatchState : null, this)) {
6567            return true;
6568        }
6569
6570        if (mInputEventConsistencyVerifier != null) {
6571            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6572        }
6573        return false;
6574    }
6575
6576    /**
6577     * Dispatches a key shortcut event.
6578     *
6579     * @param event The key event to be dispatched.
6580     * @return True if the event was handled by the view, false otherwise.
6581     */
6582    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6583        return onKeyShortcut(event.getKeyCode(), event);
6584    }
6585
6586    /**
6587     * Pass the touch screen motion event down to the target view, or this
6588     * view if it is the target.
6589     *
6590     * @param event The motion event to be dispatched.
6591     * @return True if the event was handled by the view, false otherwise.
6592     */
6593    public boolean dispatchTouchEvent(MotionEvent event) {
6594        if (mInputEventConsistencyVerifier != null) {
6595            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6596        }
6597
6598        if (onFilterTouchEventForSecurity(event)) {
6599            //noinspection SimplifiableIfStatement
6600            ListenerInfo li = mListenerInfo;
6601            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6602                    && li.mOnTouchListener.onTouch(this, event)) {
6603                return true;
6604            }
6605
6606            if (onTouchEvent(event)) {
6607                return true;
6608            }
6609        }
6610
6611        if (mInputEventConsistencyVerifier != null) {
6612            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6613        }
6614        return false;
6615    }
6616
6617    /**
6618     * Filter the touch event to apply security policies.
6619     *
6620     * @param event The motion event to be filtered.
6621     * @return True if the event should be dispatched, false if the event should be dropped.
6622     *
6623     * @see #getFilterTouchesWhenObscured
6624     */
6625    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6626        //noinspection RedundantIfStatement
6627        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6628                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6629            // Window is obscured, drop this touch.
6630            return false;
6631        }
6632        return true;
6633    }
6634
6635    /**
6636     * Pass a trackball motion event down to the focused view.
6637     *
6638     * @param event The motion event to be dispatched.
6639     * @return True if the event was handled by the view, false otherwise.
6640     */
6641    public boolean dispatchTrackballEvent(MotionEvent event) {
6642        if (mInputEventConsistencyVerifier != null) {
6643            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6644        }
6645
6646        return onTrackballEvent(event);
6647    }
6648
6649    /**
6650     * Dispatch a generic motion event.
6651     * <p>
6652     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6653     * are delivered to the view under the pointer.  All other generic motion events are
6654     * delivered to the focused view.  Hover events are handled specially and are delivered
6655     * to {@link #onHoverEvent(MotionEvent)}.
6656     * </p>
6657     *
6658     * @param event The motion event to be dispatched.
6659     * @return True if the event was handled by the view, false otherwise.
6660     */
6661    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6662        if (mInputEventConsistencyVerifier != null) {
6663            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6664        }
6665
6666        final int source = event.getSource();
6667        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6668            final int action = event.getAction();
6669            if (action == MotionEvent.ACTION_HOVER_ENTER
6670                    || action == MotionEvent.ACTION_HOVER_MOVE
6671                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6672                if (dispatchHoverEvent(event)) {
6673                    return true;
6674                }
6675            } else if (dispatchGenericPointerEvent(event)) {
6676                return true;
6677            }
6678        } else if (dispatchGenericFocusedEvent(event)) {
6679            return true;
6680        }
6681
6682        if (dispatchGenericMotionEventInternal(event)) {
6683            return true;
6684        }
6685
6686        if (mInputEventConsistencyVerifier != null) {
6687            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6688        }
6689        return false;
6690    }
6691
6692    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6693        //noinspection SimplifiableIfStatement
6694        ListenerInfo li = mListenerInfo;
6695        if (li != null && li.mOnGenericMotionListener != null
6696                && (mViewFlags & ENABLED_MASK) == ENABLED
6697                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6698            return true;
6699        }
6700
6701        if (onGenericMotionEvent(event)) {
6702            return true;
6703        }
6704
6705        if (mInputEventConsistencyVerifier != null) {
6706            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6707        }
6708        return false;
6709    }
6710
6711    /**
6712     * Dispatch a hover event.
6713     * <p>
6714     * Do not call this method directly.
6715     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6716     * </p>
6717     *
6718     * @param event The motion event to be dispatched.
6719     * @return True if the event was handled by the view, false otherwise.
6720     */
6721    protected boolean dispatchHoverEvent(MotionEvent event) {
6722        //noinspection SimplifiableIfStatement
6723        ListenerInfo li = mListenerInfo;
6724        if (li != null && li.mOnHoverListener != null
6725                && (mViewFlags & ENABLED_MASK) == ENABLED
6726                && li.mOnHoverListener.onHover(this, event)) {
6727            return true;
6728        }
6729
6730        return onHoverEvent(event);
6731    }
6732
6733    /**
6734     * Returns true if the view has a child to which it has recently sent
6735     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
6736     * it does not have a hovered child, then it must be the innermost hovered view.
6737     * @hide
6738     */
6739    protected boolean hasHoveredChild() {
6740        return false;
6741    }
6742
6743    /**
6744     * Dispatch a generic motion event to the view under the first pointer.
6745     * <p>
6746     * Do not call this method directly.
6747     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6748     * </p>
6749     *
6750     * @param event The motion event to be dispatched.
6751     * @return True if the event was handled by the view, false otherwise.
6752     */
6753    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
6754        return false;
6755    }
6756
6757    /**
6758     * Dispatch a generic motion event to the currently focused view.
6759     * <p>
6760     * Do not call this method directly.
6761     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6762     * </p>
6763     *
6764     * @param event The motion event to be dispatched.
6765     * @return True if the event was handled by the view, false otherwise.
6766     */
6767    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
6768        return false;
6769    }
6770
6771    /**
6772     * Dispatch a pointer event.
6773     * <p>
6774     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
6775     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
6776     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
6777     * and should not be expected to handle other pointing device features.
6778     * </p>
6779     *
6780     * @param event The motion event to be dispatched.
6781     * @return True if the event was handled by the view, false otherwise.
6782     * @hide
6783     */
6784    public final boolean dispatchPointerEvent(MotionEvent event) {
6785        if (event.isTouchEvent()) {
6786            return dispatchTouchEvent(event);
6787        } else {
6788            return dispatchGenericMotionEvent(event);
6789        }
6790    }
6791
6792    /**
6793     * Called when the window containing this view gains or loses window focus.
6794     * ViewGroups should override to route to their children.
6795     *
6796     * @param hasFocus True if the window containing this view now has focus,
6797     *        false otherwise.
6798     */
6799    public void dispatchWindowFocusChanged(boolean hasFocus) {
6800        onWindowFocusChanged(hasFocus);
6801    }
6802
6803    /**
6804     * Called when the window containing this view gains or loses focus.  Note
6805     * that this is separate from view focus: to receive key events, both
6806     * your view and its window must have focus.  If a window is displayed
6807     * on top of yours that takes input focus, then your own window will lose
6808     * focus but the view focus will remain unchanged.
6809     *
6810     * @param hasWindowFocus True if the window containing this view now has
6811     *        focus, false otherwise.
6812     */
6813    public void onWindowFocusChanged(boolean hasWindowFocus) {
6814        InputMethodManager imm = InputMethodManager.peekInstance();
6815        if (!hasWindowFocus) {
6816            if (isPressed()) {
6817                setPressed(false);
6818            }
6819            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6820                imm.focusOut(this);
6821            }
6822            removeLongPressCallback();
6823            removeTapCallback();
6824            onFocusLost();
6825        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
6826            imm.focusIn(this);
6827        }
6828        refreshDrawableState();
6829    }
6830
6831    /**
6832     * Returns true if this view is in a window that currently has window focus.
6833     * Note that this is not the same as the view itself having focus.
6834     *
6835     * @return True if this view is in a window that currently has window focus.
6836     */
6837    public boolean hasWindowFocus() {
6838        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
6839    }
6840
6841    /**
6842     * Dispatch a view visibility change down the view hierarchy.
6843     * ViewGroups should override to route to their children.
6844     * @param changedView The view whose visibility changed. Could be 'this' or
6845     * an ancestor view.
6846     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6847     * {@link #INVISIBLE} or {@link #GONE}.
6848     */
6849    protected void dispatchVisibilityChanged(View changedView, int visibility) {
6850        onVisibilityChanged(changedView, visibility);
6851    }
6852
6853    /**
6854     * Called when the visibility of the view or an ancestor of the view is changed.
6855     * @param changedView The view whose visibility changed. Could be 'this' or
6856     * an ancestor view.
6857     * @param visibility The new visibility of changedView: {@link #VISIBLE},
6858     * {@link #INVISIBLE} or {@link #GONE}.
6859     */
6860    protected void onVisibilityChanged(View changedView, int visibility) {
6861        if (visibility == VISIBLE) {
6862            if (mAttachInfo != null) {
6863                initialAwakenScrollBars();
6864            } else {
6865                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
6866            }
6867        }
6868    }
6869
6870    /**
6871     * Dispatch a hint about whether this view is displayed. For instance, when
6872     * a View moves out of the screen, it might receives a display hint indicating
6873     * the view is not displayed. Applications should not <em>rely</em> on this hint
6874     * as there is no guarantee that they will receive one.
6875     *
6876     * @param hint A hint about whether or not this view is displayed:
6877     * {@link #VISIBLE} or {@link #INVISIBLE}.
6878     */
6879    public void dispatchDisplayHint(int hint) {
6880        onDisplayHint(hint);
6881    }
6882
6883    /**
6884     * Gives this view a hint about whether is displayed or not. For instance, when
6885     * a View moves out of the screen, it might receives a display hint indicating
6886     * the view is not displayed. Applications should not <em>rely</em> on this hint
6887     * as there is no guarantee that they will receive one.
6888     *
6889     * @param hint A hint about whether or not this view is displayed:
6890     * {@link #VISIBLE} or {@link #INVISIBLE}.
6891     */
6892    protected void onDisplayHint(int hint) {
6893    }
6894
6895    /**
6896     * Dispatch a window visibility change down the view hierarchy.
6897     * ViewGroups should override to route to their children.
6898     *
6899     * @param visibility The new visibility of the window.
6900     *
6901     * @see #onWindowVisibilityChanged(int)
6902     */
6903    public void dispatchWindowVisibilityChanged(int visibility) {
6904        onWindowVisibilityChanged(visibility);
6905    }
6906
6907    /**
6908     * Called when the window containing has change its visibility
6909     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
6910     * that this tells you whether or not your window is being made visible
6911     * to the window manager; this does <em>not</em> tell you whether or not
6912     * your window is obscured by other windows on the screen, even if it
6913     * is itself visible.
6914     *
6915     * @param visibility The new visibility of the window.
6916     */
6917    protected void onWindowVisibilityChanged(int visibility) {
6918        if (visibility == VISIBLE) {
6919            initialAwakenScrollBars();
6920        }
6921    }
6922
6923    /**
6924     * Returns the current visibility of the window this view is attached to
6925     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6926     *
6927     * @return Returns the current visibility of the view's window.
6928     */
6929    public int getWindowVisibility() {
6930        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6931    }
6932
6933    /**
6934     * Retrieve the overall visible display size in which the window this view is
6935     * attached to has been positioned in.  This takes into account screen
6936     * decorations above the window, for both cases where the window itself
6937     * is being position inside of them or the window is being placed under
6938     * then and covered insets are used for the window to position its content
6939     * inside.  In effect, this tells you the available area where content can
6940     * be placed and remain visible to users.
6941     *
6942     * <p>This function requires an IPC back to the window manager to retrieve
6943     * the requested information, so should not be used in performance critical
6944     * code like drawing.
6945     *
6946     * @param outRect Filled in with the visible display frame.  If the view
6947     * is not attached to a window, this is simply the raw display size.
6948     */
6949    public void getWindowVisibleDisplayFrame(Rect outRect) {
6950        if (mAttachInfo != null) {
6951            try {
6952                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6953            } catch (RemoteException e) {
6954                return;
6955            }
6956            // XXX This is really broken, and probably all needs to be done
6957            // in the window manager, and we need to know more about whether
6958            // we want the area behind or in front of the IME.
6959            final Rect insets = mAttachInfo.mVisibleInsets;
6960            outRect.left += insets.left;
6961            outRect.top += insets.top;
6962            outRect.right -= insets.right;
6963            outRect.bottom -= insets.bottom;
6964            return;
6965        }
6966        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6967        d.getRectSize(outRect);
6968    }
6969
6970    /**
6971     * Dispatch a notification about a resource configuration change down
6972     * the view hierarchy.
6973     * ViewGroups should override to route to their children.
6974     *
6975     * @param newConfig The new resource configuration.
6976     *
6977     * @see #onConfigurationChanged(android.content.res.Configuration)
6978     */
6979    public void dispatchConfigurationChanged(Configuration newConfig) {
6980        onConfigurationChanged(newConfig);
6981    }
6982
6983    /**
6984     * Called when the current configuration of the resources being used
6985     * by the application have changed.  You can use this to decide when
6986     * to reload resources that can changed based on orientation and other
6987     * configuration characterstics.  You only need to use this if you are
6988     * not relying on the normal {@link android.app.Activity} mechanism of
6989     * recreating the activity instance upon a configuration change.
6990     *
6991     * @param newConfig The new resource configuration.
6992     */
6993    protected void onConfigurationChanged(Configuration newConfig) {
6994    }
6995
6996    /**
6997     * Private function to aggregate all per-view attributes in to the view
6998     * root.
6999     */
7000    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7001        performCollectViewAttributes(attachInfo, visibility);
7002    }
7003
7004    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7005        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7006            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7007                attachInfo.mKeepScreenOn = true;
7008            }
7009            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7010            ListenerInfo li = mListenerInfo;
7011            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7012                attachInfo.mHasSystemUiListeners = true;
7013            }
7014        }
7015    }
7016
7017    void needGlobalAttributesUpdate(boolean force) {
7018        final AttachInfo ai = mAttachInfo;
7019        if (ai != null) {
7020            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7021                    || ai.mHasSystemUiListeners) {
7022                ai.mRecomputeGlobalAttributes = true;
7023            }
7024        }
7025    }
7026
7027    /**
7028     * Returns whether the device is currently in touch mode.  Touch mode is entered
7029     * once the user begins interacting with the device by touch, and affects various
7030     * things like whether focus is always visible to the user.
7031     *
7032     * @return Whether the device is in touch mode.
7033     */
7034    @ViewDebug.ExportedProperty
7035    public boolean isInTouchMode() {
7036        if (mAttachInfo != null) {
7037            return mAttachInfo.mInTouchMode;
7038        } else {
7039            return ViewRootImpl.isInTouchMode();
7040        }
7041    }
7042
7043    /**
7044     * Returns the context the view is running in, through which it can
7045     * access the current theme, resources, etc.
7046     *
7047     * @return The view's Context.
7048     */
7049    @ViewDebug.CapturedViewProperty
7050    public final Context getContext() {
7051        return mContext;
7052    }
7053
7054    /**
7055     * Handle a key event before it is processed by any input method
7056     * associated with the view hierarchy.  This can be used to intercept
7057     * key events in special situations before the IME consumes them; a
7058     * typical example would be handling the BACK key to update the application's
7059     * UI instead of allowing the IME to see it and close itself.
7060     *
7061     * @param keyCode The value in event.getKeyCode().
7062     * @param event Description of the key event.
7063     * @return If you handled the event, return true. If you want to allow the
7064     *         event to be handled by the next receiver, return false.
7065     */
7066    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7067        return false;
7068    }
7069
7070    /**
7071     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7072     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7073     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7074     * is released, if the view is enabled and clickable.
7075     *
7076     * @param keyCode A key code that represents the button pressed, from
7077     *                {@link android.view.KeyEvent}.
7078     * @param event   The KeyEvent object that defines the button action.
7079     */
7080    public boolean onKeyDown(int keyCode, KeyEvent event) {
7081        boolean result = false;
7082
7083        switch (keyCode) {
7084            case KeyEvent.KEYCODE_DPAD_CENTER:
7085            case KeyEvent.KEYCODE_ENTER: {
7086                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7087                    return true;
7088                }
7089                // Long clickable items don't necessarily have to be clickable
7090                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7091                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7092                        (event.getRepeatCount() == 0)) {
7093                    setPressed(true);
7094                    checkForLongClick(0);
7095                    return true;
7096                }
7097                break;
7098            }
7099        }
7100        return result;
7101    }
7102
7103    /**
7104     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7105     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7106     * the event).
7107     */
7108    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7109        return false;
7110    }
7111
7112    /**
7113     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7114     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7115     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7116     * {@link KeyEvent#KEYCODE_ENTER} is released.
7117     *
7118     * @param keyCode A key code that represents the button pressed, from
7119     *                {@link android.view.KeyEvent}.
7120     * @param event   The KeyEvent object that defines the button action.
7121     */
7122    public boolean onKeyUp(int keyCode, KeyEvent event) {
7123        boolean result = false;
7124
7125        switch (keyCode) {
7126            case KeyEvent.KEYCODE_DPAD_CENTER:
7127            case KeyEvent.KEYCODE_ENTER: {
7128                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7129                    return true;
7130                }
7131                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7132                    setPressed(false);
7133
7134                    if (!mHasPerformedLongPress) {
7135                        // This is a tap, so remove the longpress check
7136                        removeLongPressCallback();
7137
7138                        result = performClick();
7139                    }
7140                }
7141                break;
7142            }
7143        }
7144        return result;
7145    }
7146
7147    /**
7148     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7149     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7150     * the event).
7151     *
7152     * @param keyCode     A key code that represents the button pressed, from
7153     *                    {@link android.view.KeyEvent}.
7154     * @param repeatCount The number of times the action was made.
7155     * @param event       The KeyEvent object that defines the button action.
7156     */
7157    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7158        return false;
7159    }
7160
7161    /**
7162     * Called on the focused view when a key shortcut event is not handled.
7163     * Override this method to implement local key shortcuts for the View.
7164     * Key shortcuts can also be implemented by setting the
7165     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7166     *
7167     * @param keyCode The value in event.getKeyCode().
7168     * @param event Description of the key event.
7169     * @return If you handled the event, return true. If you want to allow the
7170     *         event to be handled by the next receiver, return false.
7171     */
7172    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7173        return false;
7174    }
7175
7176    /**
7177     * Check whether the called view is a text editor, in which case it
7178     * would make sense to automatically display a soft input window for
7179     * it.  Subclasses should override this if they implement
7180     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7181     * a call on that method would return a non-null InputConnection, and
7182     * they are really a first-class editor that the user would normally
7183     * start typing on when the go into a window containing your view.
7184     *
7185     * <p>The default implementation always returns false.  This does
7186     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7187     * will not be called or the user can not otherwise perform edits on your
7188     * view; it is just a hint to the system that this is not the primary
7189     * purpose of this view.
7190     *
7191     * @return Returns true if this view is a text editor, else false.
7192     */
7193    public boolean onCheckIsTextEditor() {
7194        return false;
7195    }
7196
7197    /**
7198     * Create a new InputConnection for an InputMethod to interact
7199     * with the view.  The default implementation returns null, since it doesn't
7200     * support input methods.  You can override this to implement such support.
7201     * This is only needed for views that take focus and text input.
7202     *
7203     * <p>When implementing this, you probably also want to implement
7204     * {@link #onCheckIsTextEditor()} to indicate you will return a
7205     * non-null InputConnection.
7206     *
7207     * @param outAttrs Fill in with attribute information about the connection.
7208     */
7209    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7210        return null;
7211    }
7212
7213    /**
7214     * Called by the {@link android.view.inputmethod.InputMethodManager}
7215     * when a view who is not the current
7216     * input connection target is trying to make a call on the manager.  The
7217     * default implementation returns false; you can override this to return
7218     * true for certain views if you are performing InputConnection proxying
7219     * to them.
7220     * @param view The View that is making the InputMethodManager call.
7221     * @return Return true to allow the call, false to reject.
7222     */
7223    public boolean checkInputConnectionProxy(View view) {
7224        return false;
7225    }
7226
7227    /**
7228     * Show the context menu for this view. It is not safe to hold on to the
7229     * menu after returning from this method.
7230     *
7231     * You should normally not overload this method. Overload
7232     * {@link #onCreateContextMenu(ContextMenu)} or define an
7233     * {@link OnCreateContextMenuListener} to add items to the context menu.
7234     *
7235     * @param menu The context menu to populate
7236     */
7237    public void createContextMenu(ContextMenu menu) {
7238        ContextMenuInfo menuInfo = getContextMenuInfo();
7239
7240        // Sets the current menu info so all items added to menu will have
7241        // my extra info set.
7242        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7243
7244        onCreateContextMenu(menu);
7245        ListenerInfo li = mListenerInfo;
7246        if (li != null && li.mOnCreateContextMenuListener != null) {
7247            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7248        }
7249
7250        // Clear the extra information so subsequent items that aren't mine don't
7251        // have my extra info.
7252        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7253
7254        if (mParent != null) {
7255            mParent.createContextMenu(menu);
7256        }
7257    }
7258
7259    /**
7260     * Views should implement this if they have extra information to associate
7261     * with the context menu. The return result is supplied as a parameter to
7262     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7263     * callback.
7264     *
7265     * @return Extra information about the item for which the context menu
7266     *         should be shown. This information will vary across different
7267     *         subclasses of View.
7268     */
7269    protected ContextMenuInfo getContextMenuInfo() {
7270        return null;
7271    }
7272
7273    /**
7274     * Views should implement this if the view itself is going to add items to
7275     * the context menu.
7276     *
7277     * @param menu the context menu to populate
7278     */
7279    protected void onCreateContextMenu(ContextMenu menu) {
7280    }
7281
7282    /**
7283     * Implement this method to handle trackball motion events.  The
7284     * <em>relative</em> movement of the trackball since the last event
7285     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7286     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7287     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7288     * they will often be fractional values, representing the more fine-grained
7289     * movement information available from a trackball).
7290     *
7291     * @param event The motion event.
7292     * @return True if the event was handled, false otherwise.
7293     */
7294    public boolean onTrackballEvent(MotionEvent event) {
7295        return false;
7296    }
7297
7298    /**
7299     * Implement this method to handle generic motion events.
7300     * <p>
7301     * Generic motion events describe joystick movements, mouse hovers, track pad
7302     * touches, scroll wheel movements and other input events.  The
7303     * {@link MotionEvent#getSource() source} of the motion event specifies
7304     * the class of input that was received.  Implementations of this method
7305     * must examine the bits in the source before processing the event.
7306     * The following code example shows how this is done.
7307     * </p><p>
7308     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7309     * are delivered to the view under the pointer.  All other generic motion events are
7310     * delivered to the focused view.
7311     * </p>
7312     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7313     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7314     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7315     *             // process the joystick movement...
7316     *             return true;
7317     *         }
7318     *     }
7319     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7320     *         switch (event.getAction()) {
7321     *             case MotionEvent.ACTION_HOVER_MOVE:
7322     *                 // process the mouse hover movement...
7323     *                 return true;
7324     *             case MotionEvent.ACTION_SCROLL:
7325     *                 // process the scroll wheel movement...
7326     *                 return true;
7327     *         }
7328     *     }
7329     *     return super.onGenericMotionEvent(event);
7330     * }</pre>
7331     *
7332     * @param event The generic motion event being processed.
7333     * @return True if the event was handled, false otherwise.
7334     */
7335    public boolean onGenericMotionEvent(MotionEvent event) {
7336        return false;
7337    }
7338
7339    /**
7340     * Implement this method to handle hover events.
7341     * <p>
7342     * This method is called whenever a pointer is hovering into, over, or out of the
7343     * bounds of a view and the view is not currently being touched.
7344     * Hover events are represented as pointer events with action
7345     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7346     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7347     * </p>
7348     * <ul>
7349     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7350     * when the pointer enters the bounds of the view.</li>
7351     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7352     * when the pointer has already entered the bounds of the view and has moved.</li>
7353     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7354     * when the pointer has exited the bounds of the view or when the pointer is
7355     * about to go down due to a button click, tap, or similar user action that
7356     * causes the view to be touched.</li>
7357     * </ul>
7358     * <p>
7359     * The view should implement this method to return true to indicate that it is
7360     * handling the hover event, such as by changing its drawable state.
7361     * </p><p>
7362     * The default implementation calls {@link #setHovered} to update the hovered state
7363     * of the view when a hover enter or hover exit event is received, if the view
7364     * is enabled and is clickable.  The default implementation also sends hover
7365     * accessibility events.
7366     * </p>
7367     *
7368     * @param event The motion event that describes the hover.
7369     * @return True if the view handled the hover event.
7370     *
7371     * @see #isHovered
7372     * @see #setHovered
7373     * @see #onHoverChanged
7374     */
7375    public boolean onHoverEvent(MotionEvent event) {
7376        // The root view may receive hover (or touch) events that are outside the bounds of
7377        // the window.  This code ensures that we only send accessibility events for
7378        // hovers that are actually within the bounds of the root view.
7379        final int action = event.getActionMasked();
7380        if (!mSendingHoverAccessibilityEvents) {
7381            if ((action == MotionEvent.ACTION_HOVER_ENTER
7382                    || action == MotionEvent.ACTION_HOVER_MOVE)
7383                    && !hasHoveredChild()
7384                    && pointInView(event.getX(), event.getY())) {
7385                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7386                mSendingHoverAccessibilityEvents = true;
7387                requestAccessibilityFocusFromHover((int) event.getX(), (int) event.getY());
7388            }
7389        } else {
7390            if (action == MotionEvent.ACTION_HOVER_EXIT
7391                    || (action == MotionEvent.ACTION_MOVE
7392                            && !pointInView(event.getX(), event.getY()))) {
7393                mSendingHoverAccessibilityEvents = false;
7394                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7395                // If the window does not have input focus we take away accessibility
7396                // focus as soon as the user stop hovering over the view.
7397                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7398                    getViewRootImpl().setAccessibilityFocusedHost(null);
7399                }
7400            }
7401        }
7402
7403        if (isHoverable()) {
7404            switch (action) {
7405                case MotionEvent.ACTION_HOVER_ENTER:
7406                    setHovered(true);
7407                    break;
7408                case MotionEvent.ACTION_HOVER_EXIT:
7409                    setHovered(false);
7410                    break;
7411            }
7412
7413            // Dispatch the event to onGenericMotionEvent before returning true.
7414            // This is to provide compatibility with existing applications that
7415            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7416            // break because of the new default handling for hoverable views
7417            // in onHoverEvent.
7418            // Note that onGenericMotionEvent will be called by default when
7419            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7420            dispatchGenericMotionEventInternal(event);
7421            return true;
7422        }
7423
7424        return false;
7425    }
7426
7427    /**
7428     * Returns true if the view should handle {@link #onHoverEvent}
7429     * by calling {@link #setHovered} to change its hovered state.
7430     *
7431     * @return True if the view is hoverable.
7432     */
7433    private boolean isHoverable() {
7434        final int viewFlags = mViewFlags;
7435        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7436            return false;
7437        }
7438
7439        return (viewFlags & CLICKABLE) == CLICKABLE
7440                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7441    }
7442
7443    /**
7444     * Returns true if the view is currently hovered.
7445     *
7446     * @return True if the view is currently hovered.
7447     *
7448     * @see #setHovered
7449     * @see #onHoverChanged
7450     */
7451    @ViewDebug.ExportedProperty
7452    public boolean isHovered() {
7453        return (mPrivateFlags & HOVERED) != 0;
7454    }
7455
7456    /**
7457     * Sets whether the view is currently hovered.
7458     * <p>
7459     * Calling this method also changes the drawable state of the view.  This
7460     * enables the view to react to hover by using different drawable resources
7461     * to change its appearance.
7462     * </p><p>
7463     * The {@link #onHoverChanged} method is called when the hovered state changes.
7464     * </p>
7465     *
7466     * @param hovered True if the view is hovered.
7467     *
7468     * @see #isHovered
7469     * @see #onHoverChanged
7470     */
7471    public void setHovered(boolean hovered) {
7472        if (hovered) {
7473            if ((mPrivateFlags & HOVERED) == 0) {
7474                mPrivateFlags |= HOVERED;
7475                refreshDrawableState();
7476                onHoverChanged(true);
7477            }
7478        } else {
7479            if ((mPrivateFlags & HOVERED) != 0) {
7480                mPrivateFlags &= ~HOVERED;
7481                refreshDrawableState();
7482                onHoverChanged(false);
7483            }
7484        }
7485    }
7486
7487    /**
7488     * Implement this method to handle hover state changes.
7489     * <p>
7490     * This method is called whenever the hover state changes as a result of a
7491     * call to {@link #setHovered}.
7492     * </p>
7493     *
7494     * @param hovered The current hover state, as returned by {@link #isHovered}.
7495     *
7496     * @see #isHovered
7497     * @see #setHovered
7498     */
7499    public void onHoverChanged(boolean hovered) {
7500    }
7501
7502    /**
7503     * Implement this method to handle touch screen motion events.
7504     *
7505     * @param event The motion event.
7506     * @return True if the event was handled, false otherwise.
7507     */
7508    public boolean onTouchEvent(MotionEvent event) {
7509        final int viewFlags = mViewFlags;
7510
7511        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7512            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7513                setPressed(false);
7514            }
7515            // A disabled view that is clickable still consumes the touch
7516            // events, it just doesn't respond to them.
7517            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7518                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7519        }
7520
7521        if (mTouchDelegate != null) {
7522            if (mTouchDelegate.onTouchEvent(event)) {
7523                return true;
7524            }
7525        }
7526
7527        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7528                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7529            switch (event.getAction()) {
7530                case MotionEvent.ACTION_UP:
7531                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7532                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7533                        // take focus if we don't have it already and we should in
7534                        // touch mode.
7535                        boolean focusTaken = false;
7536                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7537                            focusTaken = requestFocus();
7538                        }
7539
7540                        if (prepressed) {
7541                            // The button is being released before we actually
7542                            // showed it as pressed.  Make it show the pressed
7543                            // state now (before scheduling the click) to ensure
7544                            // the user sees it.
7545                            setPressed(true);
7546                       }
7547
7548                        if (!mHasPerformedLongPress) {
7549                            // This is a tap, so remove the longpress check
7550                            removeLongPressCallback();
7551
7552                            // Only perform take click actions if we were in the pressed state
7553                            if (!focusTaken) {
7554                                // Use a Runnable and post this rather than calling
7555                                // performClick directly. This lets other visual state
7556                                // of the view update before click actions start.
7557                                if (mPerformClick == null) {
7558                                    mPerformClick = new PerformClick();
7559                                }
7560                                if (!post(mPerformClick)) {
7561                                    performClick();
7562                                }
7563                            }
7564                        }
7565
7566                        if (mUnsetPressedState == null) {
7567                            mUnsetPressedState = new UnsetPressedState();
7568                        }
7569
7570                        if (prepressed) {
7571                            postDelayed(mUnsetPressedState,
7572                                    ViewConfiguration.getPressedStateDuration());
7573                        } else if (!post(mUnsetPressedState)) {
7574                            // If the post failed, unpress right now
7575                            mUnsetPressedState.run();
7576                        }
7577                        removeTapCallback();
7578                    }
7579                    break;
7580
7581                case MotionEvent.ACTION_DOWN:
7582                    mHasPerformedLongPress = false;
7583
7584                    if (performButtonActionOnTouchDown(event)) {
7585                        break;
7586                    }
7587
7588                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7589                    boolean isInScrollingContainer = isInScrollingContainer();
7590
7591                    // For views inside a scrolling container, delay the pressed feedback for
7592                    // a short period in case this is a scroll.
7593                    if (isInScrollingContainer) {
7594                        mPrivateFlags |= PREPRESSED;
7595                        if (mPendingCheckForTap == null) {
7596                            mPendingCheckForTap = new CheckForTap();
7597                        }
7598                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7599                    } else {
7600                        // Not inside a scrolling container, so show the feedback right away
7601                        setPressed(true);
7602                        checkForLongClick(0);
7603                    }
7604                    break;
7605
7606                case MotionEvent.ACTION_CANCEL:
7607                    setPressed(false);
7608                    removeTapCallback();
7609                    break;
7610
7611                case MotionEvent.ACTION_MOVE:
7612                    final int x = (int) event.getX();
7613                    final int y = (int) event.getY();
7614
7615                    // Be lenient about moving outside of buttons
7616                    if (!pointInView(x, y, mTouchSlop)) {
7617                        // Outside button
7618                        removeTapCallback();
7619                        if ((mPrivateFlags & PRESSED) != 0) {
7620                            // Remove any future long press/tap checks
7621                            removeLongPressCallback();
7622
7623                            setPressed(false);
7624                        }
7625                    }
7626                    break;
7627            }
7628            return true;
7629        }
7630
7631        return false;
7632    }
7633
7634    /**
7635     * @hide
7636     */
7637    public boolean isInScrollingContainer() {
7638        ViewParent p = getParent();
7639        while (p != null && p instanceof ViewGroup) {
7640            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7641                return true;
7642            }
7643            p = p.getParent();
7644        }
7645        return false;
7646    }
7647
7648    /**
7649     * Remove the longpress detection timer.
7650     */
7651    private void removeLongPressCallback() {
7652        if (mPendingCheckForLongPress != null) {
7653          removeCallbacks(mPendingCheckForLongPress);
7654        }
7655    }
7656
7657    /**
7658     * Remove the pending click action
7659     */
7660    private void removePerformClickCallback() {
7661        if (mPerformClick != null) {
7662            removeCallbacks(mPerformClick);
7663        }
7664    }
7665
7666    /**
7667     * Remove the prepress detection timer.
7668     */
7669    private void removeUnsetPressCallback() {
7670        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7671            setPressed(false);
7672            removeCallbacks(mUnsetPressedState);
7673        }
7674    }
7675
7676    /**
7677     * Remove the tap detection timer.
7678     */
7679    private void removeTapCallback() {
7680        if (mPendingCheckForTap != null) {
7681            mPrivateFlags &= ~PREPRESSED;
7682            removeCallbacks(mPendingCheckForTap);
7683        }
7684    }
7685
7686    /**
7687     * Cancels a pending long press.  Your subclass can use this if you
7688     * want the context menu to come up if the user presses and holds
7689     * at the same place, but you don't want it to come up if they press
7690     * and then move around enough to cause scrolling.
7691     */
7692    public void cancelLongPress() {
7693        removeLongPressCallback();
7694
7695        /*
7696         * The prepressed state handled by the tap callback is a display
7697         * construct, but the tap callback will post a long press callback
7698         * less its own timeout. Remove it here.
7699         */
7700        removeTapCallback();
7701    }
7702
7703    /**
7704     * Remove the pending callback for sending a
7705     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7706     */
7707    private void removeSendViewScrolledAccessibilityEventCallback() {
7708        if (mSendViewScrolledAccessibilityEvent != null) {
7709            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7710        }
7711    }
7712
7713    /**
7714     * Sets the TouchDelegate for this View.
7715     */
7716    public void setTouchDelegate(TouchDelegate delegate) {
7717        mTouchDelegate = delegate;
7718    }
7719
7720    /**
7721     * Gets the TouchDelegate for this View.
7722     */
7723    public TouchDelegate getTouchDelegate() {
7724        return mTouchDelegate;
7725    }
7726
7727    /**
7728     * Set flags controlling behavior of this view.
7729     *
7730     * @param flags Constant indicating the value which should be set
7731     * @param mask Constant indicating the bit range that should be changed
7732     */
7733    void setFlags(int flags, int mask) {
7734        int old = mViewFlags;
7735        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
7736
7737        int changed = mViewFlags ^ old;
7738        if (changed == 0) {
7739            return;
7740        }
7741        int privateFlags = mPrivateFlags;
7742
7743        /* Check if the FOCUSABLE bit has changed */
7744        if (((changed & FOCUSABLE_MASK) != 0) &&
7745                ((privateFlags & HAS_BOUNDS) !=0)) {
7746            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
7747                    && ((privateFlags & FOCUSED) != 0)) {
7748                /* Give up focus if we are no longer focusable */
7749                clearFocus();
7750            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
7751                    && ((privateFlags & FOCUSED) == 0)) {
7752                /*
7753                 * Tell the view system that we are now available to take focus
7754                 * if no one else already has it.
7755                 */
7756                if (mParent != null) mParent.focusableViewAvailable(this);
7757            }
7758            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7759                notifyAccessibilityStateChanged();
7760            }
7761        }
7762
7763        if ((flags & VISIBILITY_MASK) == VISIBLE) {
7764            if ((changed & VISIBILITY_MASK) != 0) {
7765                /*
7766                 * If this view is becoming visible, invalidate it in case it changed while
7767                 * it was not visible. Marking it drawn ensures that the invalidation will
7768                 * go through.
7769                 */
7770                mPrivateFlags |= DRAWN;
7771                invalidate(true);
7772
7773                needGlobalAttributesUpdate(true);
7774
7775                // a view becoming visible is worth notifying the parent
7776                // about in case nothing has focus.  even if this specific view
7777                // isn't focusable, it may contain something that is, so let
7778                // the root view try to give this focus if nothing else does.
7779                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
7780                    mParent.focusableViewAvailable(this);
7781                }
7782            }
7783        }
7784
7785        /* Check if the GONE bit has changed */
7786        if ((changed & GONE) != 0) {
7787            needGlobalAttributesUpdate(false);
7788            requestLayout();
7789
7790            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
7791                if (hasFocus()) clearFocus();
7792                clearAccessibilityFocus();
7793                destroyDrawingCache();
7794                if (mParent instanceof View) {
7795                    // GONE views noop invalidation, so invalidate the parent
7796                    ((View) mParent).invalidate(true);
7797                }
7798                // Mark the view drawn to ensure that it gets invalidated properly the next
7799                // time it is visible and gets invalidated
7800                mPrivateFlags |= DRAWN;
7801            }
7802            if (mAttachInfo != null) {
7803                mAttachInfo.mViewVisibilityChanged = true;
7804            }
7805        }
7806
7807        /* Check if the VISIBLE bit has changed */
7808        if ((changed & INVISIBLE) != 0) {
7809            needGlobalAttributesUpdate(false);
7810            /*
7811             * If this view is becoming invisible, set the DRAWN flag so that
7812             * the next invalidate() will not be skipped.
7813             */
7814            mPrivateFlags |= DRAWN;
7815
7816            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
7817                // root view becoming invisible shouldn't clear focus and accessibility focus
7818                if (getRootView() != this) {
7819                    clearFocus();
7820                    clearAccessibilityFocus();
7821                }
7822            }
7823            if (mAttachInfo != null) {
7824                mAttachInfo.mViewVisibilityChanged = true;
7825            }
7826        }
7827
7828        if ((changed & VISIBILITY_MASK) != 0) {
7829            if (mParent instanceof ViewGroup) {
7830                ((ViewGroup) mParent).onChildVisibilityChanged(this,
7831                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
7832                ((View) mParent).invalidate(true);
7833            } else if (mParent != null) {
7834                mParent.invalidateChild(this, null);
7835            }
7836            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
7837        }
7838
7839        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
7840            destroyDrawingCache();
7841        }
7842
7843        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
7844            destroyDrawingCache();
7845            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7846            invalidateParentCaches();
7847        }
7848
7849        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
7850            destroyDrawingCache();
7851            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7852        }
7853
7854        if ((changed & DRAW_MASK) != 0) {
7855            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
7856                if (mBackground != null) {
7857                    mPrivateFlags &= ~SKIP_DRAW;
7858                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
7859                } else {
7860                    mPrivateFlags |= SKIP_DRAW;
7861                }
7862            } else {
7863                mPrivateFlags &= ~SKIP_DRAW;
7864            }
7865            requestLayout();
7866            invalidate(true);
7867        }
7868
7869        if ((changed & KEEP_SCREEN_ON) != 0) {
7870            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
7871                mParent.recomputeViewAttributes(this);
7872            }
7873        }
7874
7875        if (AccessibilityManager.getInstance(mContext).isEnabled()
7876                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
7877                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
7878            notifyAccessibilityStateChanged();
7879        }
7880    }
7881
7882    /**
7883     * Change the view's z order in the tree, so it's on top of other sibling
7884     * views
7885     */
7886    public void bringToFront() {
7887        if (mParent != null) {
7888            mParent.bringChildToFront(this);
7889        }
7890    }
7891
7892    /**
7893     * This is called in response to an internal scroll in this view (i.e., the
7894     * view scrolled its own contents). This is typically as a result of
7895     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
7896     * called.
7897     *
7898     * @param l Current horizontal scroll origin.
7899     * @param t Current vertical scroll origin.
7900     * @param oldl Previous horizontal scroll origin.
7901     * @param oldt Previous vertical scroll origin.
7902     */
7903    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
7904        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
7905            postSendViewScrolledAccessibilityEventCallback();
7906        }
7907
7908        mBackgroundSizeChanged = true;
7909
7910        final AttachInfo ai = mAttachInfo;
7911        if (ai != null) {
7912            ai.mViewScrollChanged = true;
7913        }
7914    }
7915
7916    /**
7917     * Interface definition for a callback to be invoked when the layout bounds of a view
7918     * changes due to layout processing.
7919     */
7920    public interface OnLayoutChangeListener {
7921        /**
7922         * Called when the focus state of a view has changed.
7923         *
7924         * @param v The view whose state has changed.
7925         * @param left The new value of the view's left property.
7926         * @param top The new value of the view's top property.
7927         * @param right The new value of the view's right property.
7928         * @param bottom The new value of the view's bottom property.
7929         * @param oldLeft The previous value of the view's left property.
7930         * @param oldTop The previous value of the view's top property.
7931         * @param oldRight The previous value of the view's right property.
7932         * @param oldBottom The previous value of the view's bottom property.
7933         */
7934        void onLayoutChange(View v, int left, int top, int right, int bottom,
7935            int oldLeft, int oldTop, int oldRight, int oldBottom);
7936    }
7937
7938    /**
7939     * This is called during layout when the size of this view has changed. If
7940     * you were just added to the view hierarchy, you're called with the old
7941     * values of 0.
7942     *
7943     * @param w Current width of this view.
7944     * @param h Current height of this view.
7945     * @param oldw Old width of this view.
7946     * @param oldh Old height of this view.
7947     */
7948    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7949    }
7950
7951    /**
7952     * Called by draw to draw the child views. This may be overridden
7953     * by derived classes to gain control just before its children are drawn
7954     * (but after its own view has been drawn).
7955     * @param canvas the canvas on which to draw the view
7956     */
7957    protected void dispatchDraw(Canvas canvas) {
7958
7959    }
7960
7961    /**
7962     * Gets the parent of this view. Note that the parent is a
7963     * ViewParent and not necessarily a View.
7964     *
7965     * @return Parent of this view.
7966     */
7967    public final ViewParent getParent() {
7968        return mParent;
7969    }
7970
7971    /**
7972     * Set the horizontal scrolled position of your view. This will cause a call to
7973     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7974     * invalidated.
7975     * @param value the x position to scroll to
7976     */
7977    public void setScrollX(int value) {
7978        scrollTo(value, mScrollY);
7979    }
7980
7981    /**
7982     * Set the vertical scrolled position of your view. This will cause a call to
7983     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7984     * invalidated.
7985     * @param value the y position to scroll to
7986     */
7987    public void setScrollY(int value) {
7988        scrollTo(mScrollX, value);
7989    }
7990
7991    /**
7992     * Return the scrolled left position of this view. This is the left edge of
7993     * the displayed part of your view. You do not need to draw any pixels
7994     * farther left, since those are outside of the frame of your view on
7995     * screen.
7996     *
7997     * @return The left edge of the displayed part of your view, in pixels.
7998     */
7999    public final int getScrollX() {
8000        return mScrollX;
8001    }
8002
8003    /**
8004     * Return the scrolled top position of this view. This is the top edge of
8005     * the displayed part of your view. You do not need to draw any pixels above
8006     * it, since those are outside of the frame of your view on screen.
8007     *
8008     * @return The top edge of the displayed part of your view, in pixels.
8009     */
8010    public final int getScrollY() {
8011        return mScrollY;
8012    }
8013
8014    /**
8015     * Return the width of the your view.
8016     *
8017     * @return The width of your view, in pixels.
8018     */
8019    @ViewDebug.ExportedProperty(category = "layout")
8020    public final int getWidth() {
8021        return mRight - mLeft;
8022    }
8023
8024    /**
8025     * Return the height of your view.
8026     *
8027     * @return The height of your view, in pixels.
8028     */
8029    @ViewDebug.ExportedProperty(category = "layout")
8030    public final int getHeight() {
8031        return mBottom - mTop;
8032    }
8033
8034    /**
8035     * Return the visible drawing bounds of your view. Fills in the output
8036     * rectangle with the values from getScrollX(), getScrollY(),
8037     * getWidth(), and getHeight().
8038     *
8039     * @param outRect The (scrolled) drawing bounds of the view.
8040     */
8041    public void getDrawingRect(Rect outRect) {
8042        outRect.left = mScrollX;
8043        outRect.top = mScrollY;
8044        outRect.right = mScrollX + (mRight - mLeft);
8045        outRect.bottom = mScrollY + (mBottom - mTop);
8046    }
8047
8048    /**
8049     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8050     * raw width component (that is the result is masked by
8051     * {@link #MEASURED_SIZE_MASK}).
8052     *
8053     * @return The raw measured width of this view.
8054     */
8055    public final int getMeasuredWidth() {
8056        return mMeasuredWidth & MEASURED_SIZE_MASK;
8057    }
8058
8059    /**
8060     * Return the full width measurement information for this view as computed
8061     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8062     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8063     * This should be used during measurement and layout calculations only. Use
8064     * {@link #getWidth()} to see how wide a view is after layout.
8065     *
8066     * @return The measured width of this view as a bit mask.
8067     */
8068    public final int getMeasuredWidthAndState() {
8069        return mMeasuredWidth;
8070    }
8071
8072    /**
8073     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8074     * raw width component (that is the result is masked by
8075     * {@link #MEASURED_SIZE_MASK}).
8076     *
8077     * @return The raw measured height of this view.
8078     */
8079    public final int getMeasuredHeight() {
8080        return mMeasuredHeight & MEASURED_SIZE_MASK;
8081    }
8082
8083    /**
8084     * Return the full height measurement information for this view as computed
8085     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8086     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8087     * This should be used during measurement and layout calculations only. Use
8088     * {@link #getHeight()} to see how wide a view is after layout.
8089     *
8090     * @return The measured width of this view as a bit mask.
8091     */
8092    public final int getMeasuredHeightAndState() {
8093        return mMeasuredHeight;
8094    }
8095
8096    /**
8097     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8098     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8099     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8100     * and the height component is at the shifted bits
8101     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8102     */
8103    public final int getMeasuredState() {
8104        return (mMeasuredWidth&MEASURED_STATE_MASK)
8105                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8106                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8107    }
8108
8109    /**
8110     * The transform matrix of this view, which is calculated based on the current
8111     * roation, scale, and pivot properties.
8112     *
8113     * @see #getRotation()
8114     * @see #getScaleX()
8115     * @see #getScaleY()
8116     * @see #getPivotX()
8117     * @see #getPivotY()
8118     * @return The current transform matrix for the view
8119     */
8120    public Matrix getMatrix() {
8121        if (mTransformationInfo != null) {
8122            updateMatrix();
8123            return mTransformationInfo.mMatrix;
8124        }
8125        return Matrix.IDENTITY_MATRIX;
8126    }
8127
8128    /**
8129     * Utility function to determine if the value is far enough away from zero to be
8130     * considered non-zero.
8131     * @param value A floating point value to check for zero-ness
8132     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8133     */
8134    private static boolean nonzero(float value) {
8135        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8136    }
8137
8138    /**
8139     * Returns true if the transform matrix is the identity matrix.
8140     * Recomputes the matrix if necessary.
8141     *
8142     * @return True if the transform matrix is the identity matrix, false otherwise.
8143     */
8144    final boolean hasIdentityMatrix() {
8145        if (mTransformationInfo != null) {
8146            updateMatrix();
8147            return mTransformationInfo.mMatrixIsIdentity;
8148        }
8149        return true;
8150    }
8151
8152    void ensureTransformationInfo() {
8153        if (mTransformationInfo == null) {
8154            mTransformationInfo = new TransformationInfo();
8155        }
8156    }
8157
8158    /**
8159     * Recomputes the transform matrix if necessary.
8160     */
8161    private void updateMatrix() {
8162        final TransformationInfo info = mTransformationInfo;
8163        if (info == null) {
8164            return;
8165        }
8166        if (info.mMatrixDirty) {
8167            // transform-related properties have changed since the last time someone
8168            // asked for the matrix; recalculate it with the current values
8169
8170            // Figure out if we need to update the pivot point
8171            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8172                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8173                    info.mPrevWidth = mRight - mLeft;
8174                    info.mPrevHeight = mBottom - mTop;
8175                    info.mPivotX = info.mPrevWidth / 2f;
8176                    info.mPivotY = info.mPrevHeight / 2f;
8177                }
8178            }
8179            info.mMatrix.reset();
8180            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8181                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8182                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8183                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8184            } else {
8185                if (info.mCamera == null) {
8186                    info.mCamera = new Camera();
8187                    info.matrix3D = new Matrix();
8188                }
8189                info.mCamera.save();
8190                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8191                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8192                info.mCamera.getMatrix(info.matrix3D);
8193                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8194                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8195                        info.mPivotY + info.mTranslationY);
8196                info.mMatrix.postConcat(info.matrix3D);
8197                info.mCamera.restore();
8198            }
8199            info.mMatrixDirty = false;
8200            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8201            info.mInverseMatrixDirty = true;
8202        }
8203    }
8204
8205    /**
8206     * Utility method to retrieve the inverse of the current mMatrix property.
8207     * We cache the matrix to avoid recalculating it when transform properties
8208     * have not changed.
8209     *
8210     * @return The inverse of the current matrix of this view.
8211     */
8212    final Matrix getInverseMatrix() {
8213        final TransformationInfo info = mTransformationInfo;
8214        if (info != null) {
8215            updateMatrix();
8216            if (info.mInverseMatrixDirty) {
8217                if (info.mInverseMatrix == null) {
8218                    info.mInverseMatrix = new Matrix();
8219                }
8220                info.mMatrix.invert(info.mInverseMatrix);
8221                info.mInverseMatrixDirty = false;
8222            }
8223            return info.mInverseMatrix;
8224        }
8225        return Matrix.IDENTITY_MATRIX;
8226    }
8227
8228    /**
8229     * Gets the distance along the Z axis from the camera to this view.
8230     *
8231     * @see #setCameraDistance(float)
8232     *
8233     * @return The distance along the Z axis.
8234     */
8235    public float getCameraDistance() {
8236        ensureTransformationInfo();
8237        final float dpi = mResources.getDisplayMetrics().densityDpi;
8238        final TransformationInfo info = mTransformationInfo;
8239        if (info.mCamera == null) {
8240            info.mCamera = new Camera();
8241            info.matrix3D = new Matrix();
8242        }
8243        return -(info.mCamera.getLocationZ() * dpi);
8244    }
8245
8246    /**
8247     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8248     * views are drawn) from the camera to this view. The camera's distance
8249     * affects 3D transformations, for instance rotations around the X and Y
8250     * axis. If the rotationX or rotationY properties are changed and this view is
8251     * large (more than half the size of the screen), it is recommended to always
8252     * use a camera distance that's greater than the height (X axis rotation) or
8253     * the width (Y axis rotation) of this view.</p>
8254     *
8255     * <p>The distance of the camera from the view plane can have an affect on the
8256     * perspective distortion of the view when it is rotated around the x or y axis.
8257     * For example, a large distance will result in a large viewing angle, and there
8258     * will not be much perspective distortion of the view as it rotates. A short
8259     * distance may cause much more perspective distortion upon rotation, and can
8260     * also result in some drawing artifacts if the rotated view ends up partially
8261     * behind the camera (which is why the recommendation is to use a distance at
8262     * least as far as the size of the view, if the view is to be rotated.)</p>
8263     *
8264     * <p>The distance is expressed in "depth pixels." The default distance depends
8265     * on the screen density. For instance, on a medium density display, the
8266     * default distance is 1280. On a high density display, the default distance
8267     * is 1920.</p>
8268     *
8269     * <p>If you want to specify a distance that leads to visually consistent
8270     * results across various densities, use the following formula:</p>
8271     * <pre>
8272     * float scale = context.getResources().getDisplayMetrics().density;
8273     * view.setCameraDistance(distance * scale);
8274     * </pre>
8275     *
8276     * <p>The density scale factor of a high density display is 1.5,
8277     * and 1920 = 1280 * 1.5.</p>
8278     *
8279     * @param distance The distance in "depth pixels", if negative the opposite
8280     *        value is used
8281     *
8282     * @see #setRotationX(float)
8283     * @see #setRotationY(float)
8284     */
8285    public void setCameraDistance(float distance) {
8286        invalidateViewProperty(true, false);
8287
8288        ensureTransformationInfo();
8289        final float dpi = mResources.getDisplayMetrics().densityDpi;
8290        final TransformationInfo info = mTransformationInfo;
8291        if (info.mCamera == null) {
8292            info.mCamera = new Camera();
8293            info.matrix3D = new Matrix();
8294        }
8295
8296        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8297        info.mMatrixDirty = true;
8298
8299        invalidateViewProperty(false, false);
8300        if (mDisplayList != null) {
8301            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8302        }
8303    }
8304
8305    /**
8306     * The degrees that the view is rotated around the pivot point.
8307     *
8308     * @see #setRotation(float)
8309     * @see #getPivotX()
8310     * @see #getPivotY()
8311     *
8312     * @return The degrees of rotation.
8313     */
8314    @ViewDebug.ExportedProperty(category = "drawing")
8315    public float getRotation() {
8316        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8317    }
8318
8319    /**
8320     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8321     * result in clockwise rotation.
8322     *
8323     * @param rotation The degrees of rotation.
8324     *
8325     * @see #getRotation()
8326     * @see #getPivotX()
8327     * @see #getPivotY()
8328     * @see #setRotationX(float)
8329     * @see #setRotationY(float)
8330     *
8331     * @attr ref android.R.styleable#View_rotation
8332     */
8333    public void setRotation(float rotation) {
8334        ensureTransformationInfo();
8335        final TransformationInfo info = mTransformationInfo;
8336        if (info.mRotation != rotation) {
8337            // Double-invalidation is necessary to capture view's old and new areas
8338            invalidateViewProperty(true, false);
8339            info.mRotation = rotation;
8340            info.mMatrixDirty = true;
8341            invalidateViewProperty(false, true);
8342            if (mDisplayList != null) {
8343                mDisplayList.setRotation(rotation);
8344            }
8345        }
8346    }
8347
8348    /**
8349     * The degrees that the view is rotated around the vertical axis through the pivot point.
8350     *
8351     * @see #getPivotX()
8352     * @see #getPivotY()
8353     * @see #setRotationY(float)
8354     *
8355     * @return The degrees of Y rotation.
8356     */
8357    @ViewDebug.ExportedProperty(category = "drawing")
8358    public float getRotationY() {
8359        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8360    }
8361
8362    /**
8363     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8364     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8365     * down the y axis.
8366     *
8367     * When rotating large views, it is recommended to adjust the camera distance
8368     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8369     *
8370     * @param rotationY The degrees of Y rotation.
8371     *
8372     * @see #getRotationY()
8373     * @see #getPivotX()
8374     * @see #getPivotY()
8375     * @see #setRotation(float)
8376     * @see #setRotationX(float)
8377     * @see #setCameraDistance(float)
8378     *
8379     * @attr ref android.R.styleable#View_rotationY
8380     */
8381    public void setRotationY(float rotationY) {
8382        ensureTransformationInfo();
8383        final TransformationInfo info = mTransformationInfo;
8384        if (info.mRotationY != rotationY) {
8385            invalidateViewProperty(true, false);
8386            info.mRotationY = rotationY;
8387            info.mMatrixDirty = true;
8388            invalidateViewProperty(false, true);
8389            if (mDisplayList != null) {
8390                mDisplayList.setRotationY(rotationY);
8391            }
8392        }
8393    }
8394
8395    /**
8396     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8397     *
8398     * @see #getPivotX()
8399     * @see #getPivotY()
8400     * @see #setRotationX(float)
8401     *
8402     * @return The degrees of X rotation.
8403     */
8404    @ViewDebug.ExportedProperty(category = "drawing")
8405    public float getRotationX() {
8406        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8407    }
8408
8409    /**
8410     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8411     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8412     * x axis.
8413     *
8414     * When rotating large views, it is recommended to adjust the camera distance
8415     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8416     *
8417     * @param rotationX The degrees of X rotation.
8418     *
8419     * @see #getRotationX()
8420     * @see #getPivotX()
8421     * @see #getPivotY()
8422     * @see #setRotation(float)
8423     * @see #setRotationY(float)
8424     * @see #setCameraDistance(float)
8425     *
8426     * @attr ref android.R.styleable#View_rotationX
8427     */
8428    public void setRotationX(float rotationX) {
8429        ensureTransformationInfo();
8430        final TransformationInfo info = mTransformationInfo;
8431        if (info.mRotationX != rotationX) {
8432            invalidateViewProperty(true, false);
8433            info.mRotationX = rotationX;
8434            info.mMatrixDirty = true;
8435            invalidateViewProperty(false, true);
8436            if (mDisplayList != null) {
8437                mDisplayList.setRotationX(rotationX);
8438            }
8439        }
8440    }
8441
8442    /**
8443     * The amount that the view is scaled in x around the pivot point, as a proportion of
8444     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8445     *
8446     * <p>By default, this is 1.0f.
8447     *
8448     * @see #getPivotX()
8449     * @see #getPivotY()
8450     * @return The scaling factor.
8451     */
8452    @ViewDebug.ExportedProperty(category = "drawing")
8453    public float getScaleX() {
8454        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8455    }
8456
8457    /**
8458     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8459     * the view's unscaled width. A value of 1 means that no scaling is applied.
8460     *
8461     * @param scaleX The scaling factor.
8462     * @see #getPivotX()
8463     * @see #getPivotY()
8464     *
8465     * @attr ref android.R.styleable#View_scaleX
8466     */
8467    public void setScaleX(float scaleX) {
8468        ensureTransformationInfo();
8469        final TransformationInfo info = mTransformationInfo;
8470        if (info.mScaleX != scaleX) {
8471            invalidateViewProperty(true, false);
8472            info.mScaleX = scaleX;
8473            info.mMatrixDirty = true;
8474            invalidateViewProperty(false, true);
8475            if (mDisplayList != null) {
8476                mDisplayList.setScaleX(scaleX);
8477            }
8478        }
8479    }
8480
8481    /**
8482     * The amount that the view is scaled in y around the pivot point, as a proportion of
8483     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8484     *
8485     * <p>By default, this is 1.0f.
8486     *
8487     * @see #getPivotX()
8488     * @see #getPivotY()
8489     * @return The scaling factor.
8490     */
8491    @ViewDebug.ExportedProperty(category = "drawing")
8492    public float getScaleY() {
8493        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8494    }
8495
8496    /**
8497     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8498     * the view's unscaled width. A value of 1 means that no scaling is applied.
8499     *
8500     * @param scaleY The scaling factor.
8501     * @see #getPivotX()
8502     * @see #getPivotY()
8503     *
8504     * @attr ref android.R.styleable#View_scaleY
8505     */
8506    public void setScaleY(float scaleY) {
8507        ensureTransformationInfo();
8508        final TransformationInfo info = mTransformationInfo;
8509        if (info.mScaleY != scaleY) {
8510            invalidateViewProperty(true, false);
8511            info.mScaleY = scaleY;
8512            info.mMatrixDirty = true;
8513            invalidateViewProperty(false, true);
8514            if (mDisplayList != null) {
8515                mDisplayList.setScaleY(scaleY);
8516            }
8517        }
8518    }
8519
8520    /**
8521     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8522     * and {@link #setScaleX(float) scaled}.
8523     *
8524     * @see #getRotation()
8525     * @see #getScaleX()
8526     * @see #getScaleY()
8527     * @see #getPivotY()
8528     * @return The x location of the pivot point.
8529     *
8530     * @attr ref android.R.styleable#View_transformPivotX
8531     */
8532    @ViewDebug.ExportedProperty(category = "drawing")
8533    public float getPivotX() {
8534        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8535    }
8536
8537    /**
8538     * Sets the x location of the point around which the view is
8539     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8540     * By default, the pivot point is centered on the object.
8541     * Setting this property disables this behavior and causes the view to use only the
8542     * explicitly set pivotX and pivotY values.
8543     *
8544     * @param pivotX The x location of the pivot point.
8545     * @see #getRotation()
8546     * @see #getScaleX()
8547     * @see #getScaleY()
8548     * @see #getPivotY()
8549     *
8550     * @attr ref android.R.styleable#View_transformPivotX
8551     */
8552    public void setPivotX(float pivotX) {
8553        ensureTransformationInfo();
8554        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8555        final TransformationInfo info = mTransformationInfo;
8556        if (info.mPivotX != pivotX) {
8557            invalidateViewProperty(true, false);
8558            info.mPivotX = pivotX;
8559            info.mMatrixDirty = true;
8560            invalidateViewProperty(false, true);
8561            if (mDisplayList != null) {
8562                mDisplayList.setPivotX(pivotX);
8563            }
8564        }
8565    }
8566
8567    /**
8568     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8569     * and {@link #setScaleY(float) scaled}.
8570     *
8571     * @see #getRotation()
8572     * @see #getScaleX()
8573     * @see #getScaleY()
8574     * @see #getPivotY()
8575     * @return The y location of the pivot point.
8576     *
8577     * @attr ref android.R.styleable#View_transformPivotY
8578     */
8579    @ViewDebug.ExportedProperty(category = "drawing")
8580    public float getPivotY() {
8581        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8582    }
8583
8584    /**
8585     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8586     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8587     * Setting this property disables this behavior and causes the view to use only the
8588     * explicitly set pivotX and pivotY values.
8589     *
8590     * @param pivotY The y location of the pivot point.
8591     * @see #getRotation()
8592     * @see #getScaleX()
8593     * @see #getScaleY()
8594     * @see #getPivotY()
8595     *
8596     * @attr ref android.R.styleable#View_transformPivotY
8597     */
8598    public void setPivotY(float pivotY) {
8599        ensureTransformationInfo();
8600        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8601        final TransformationInfo info = mTransformationInfo;
8602        if (info.mPivotY != pivotY) {
8603            invalidateViewProperty(true, false);
8604            info.mPivotY = pivotY;
8605            info.mMatrixDirty = true;
8606            invalidateViewProperty(false, true);
8607            if (mDisplayList != null) {
8608                mDisplayList.setPivotY(pivotY);
8609            }
8610        }
8611    }
8612
8613    /**
8614     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8615     * completely transparent and 1 means the view is completely opaque.
8616     *
8617     * <p>By default this is 1.0f.
8618     * @return The opacity of the view.
8619     */
8620    @ViewDebug.ExportedProperty(category = "drawing")
8621    public float getAlpha() {
8622        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8623    }
8624
8625    /**
8626     * Returns whether this View has content which overlaps. This function, intended to be
8627     * overridden by specific View types, is an optimization when alpha is set on a view. If
8628     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8629     * and then composited it into place, which can be expensive. If the view has no overlapping
8630     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8631     * An example of overlapping rendering is a TextView with a background image, such as a
8632     * Button. An example of non-overlapping rendering is a TextView with no background, or
8633     * an ImageView with only the foreground image. The default implementation returns true;
8634     * subclasses should override if they have cases which can be optimized.
8635     *
8636     * @return true if the content in this view might overlap, false otherwise.
8637     */
8638    public boolean hasOverlappingRendering() {
8639        return true;
8640    }
8641
8642    /**
8643     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8644     * completely transparent and 1 means the view is completely opaque.</p>
8645     *
8646     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8647     * responsible for applying the opacity itself. Otherwise, calling this method is
8648     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8649     * setting a hardware layer.</p>
8650     *
8651     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8652     * performance implications. It is generally best to use the alpha property sparingly and
8653     * transiently, as in the case of fading animations.</p>
8654     *
8655     * @param alpha The opacity of the view.
8656     *
8657     * @see #setLayerType(int, android.graphics.Paint)
8658     *
8659     * @attr ref android.R.styleable#View_alpha
8660     */
8661    public void setAlpha(float alpha) {
8662        ensureTransformationInfo();
8663        if (mTransformationInfo.mAlpha != alpha) {
8664            mTransformationInfo.mAlpha = alpha;
8665            if (onSetAlpha((int) (alpha * 255))) {
8666                mPrivateFlags |= ALPHA_SET;
8667                // subclass is handling alpha - don't optimize rendering cache invalidation
8668                invalidateParentCaches();
8669                invalidate(true);
8670            } else {
8671                mPrivateFlags &= ~ALPHA_SET;
8672                invalidateViewProperty(true, false);
8673                if (mDisplayList != null) {
8674                    mDisplayList.setAlpha(alpha);
8675                }
8676            }
8677        }
8678    }
8679
8680    /**
8681     * Faster version of setAlpha() which performs the same steps except there are
8682     * no calls to invalidate(). The caller of this function should perform proper invalidation
8683     * on the parent and this object. The return value indicates whether the subclass handles
8684     * alpha (the return value for onSetAlpha()).
8685     *
8686     * @param alpha The new value for the alpha property
8687     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
8688     *         the new value for the alpha property is different from the old value
8689     */
8690    boolean setAlphaNoInvalidation(float alpha) {
8691        ensureTransformationInfo();
8692        if (mTransformationInfo.mAlpha != alpha) {
8693            mTransformationInfo.mAlpha = alpha;
8694            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
8695            if (subclassHandlesAlpha) {
8696                mPrivateFlags |= ALPHA_SET;
8697                return true;
8698            } else {
8699                mPrivateFlags &= ~ALPHA_SET;
8700                if (mDisplayList != null) {
8701                    mDisplayList.setAlpha(alpha);
8702                }
8703            }
8704        }
8705        return false;
8706    }
8707
8708    /**
8709     * Top position of this view relative to its parent.
8710     *
8711     * @return The top of this view, in pixels.
8712     */
8713    @ViewDebug.CapturedViewProperty
8714    public final int getTop() {
8715        return mTop;
8716    }
8717
8718    /**
8719     * Sets the top position of this view relative to its parent. This method is meant to be called
8720     * by the layout system and should not generally be called otherwise, because the property
8721     * may be changed at any time by the layout.
8722     *
8723     * @param top The top of this view, in pixels.
8724     */
8725    public final void setTop(int top) {
8726        if (top != mTop) {
8727            updateMatrix();
8728            final boolean matrixIsIdentity = mTransformationInfo == null
8729                    || mTransformationInfo.mMatrixIsIdentity;
8730            if (matrixIsIdentity) {
8731                if (mAttachInfo != null) {
8732                    int minTop;
8733                    int yLoc;
8734                    if (top < mTop) {
8735                        minTop = top;
8736                        yLoc = top - mTop;
8737                    } else {
8738                        minTop = mTop;
8739                        yLoc = 0;
8740                    }
8741                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
8742                }
8743            } else {
8744                // Double-invalidation is necessary to capture view's old and new areas
8745                invalidate(true);
8746            }
8747
8748            int width = mRight - mLeft;
8749            int oldHeight = mBottom - mTop;
8750
8751            mTop = top;
8752            if (mDisplayList != null) {
8753                mDisplayList.setTop(mTop);
8754            }
8755
8756            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8757
8758            if (!matrixIsIdentity) {
8759                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8760                    // A change in dimension means an auto-centered pivot point changes, too
8761                    mTransformationInfo.mMatrixDirty = true;
8762                }
8763                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8764                invalidate(true);
8765            }
8766            mBackgroundSizeChanged = true;
8767            invalidateParentIfNeeded();
8768        }
8769    }
8770
8771    /**
8772     * Bottom position of this view relative to its parent.
8773     *
8774     * @return The bottom of this view, in pixels.
8775     */
8776    @ViewDebug.CapturedViewProperty
8777    public final int getBottom() {
8778        return mBottom;
8779    }
8780
8781    /**
8782     * True if this view has changed since the last time being drawn.
8783     *
8784     * @return The dirty state of this view.
8785     */
8786    public boolean isDirty() {
8787        return (mPrivateFlags & DIRTY_MASK) != 0;
8788    }
8789
8790    /**
8791     * Sets the bottom position of this view relative to its parent. This method is meant to be
8792     * called by the layout system and should not generally be called otherwise, because the
8793     * property may be changed at any time by the layout.
8794     *
8795     * @param bottom The bottom of this view, in pixels.
8796     */
8797    public final void setBottom(int bottom) {
8798        if (bottom != mBottom) {
8799            updateMatrix();
8800            final boolean matrixIsIdentity = mTransformationInfo == null
8801                    || mTransformationInfo.mMatrixIsIdentity;
8802            if (matrixIsIdentity) {
8803                if (mAttachInfo != null) {
8804                    int maxBottom;
8805                    if (bottom < mBottom) {
8806                        maxBottom = mBottom;
8807                    } else {
8808                        maxBottom = bottom;
8809                    }
8810                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
8811                }
8812            } else {
8813                // Double-invalidation is necessary to capture view's old and new areas
8814                invalidate(true);
8815            }
8816
8817            int width = mRight - mLeft;
8818            int oldHeight = mBottom - mTop;
8819
8820            mBottom = bottom;
8821            if (mDisplayList != null) {
8822                mDisplayList.setBottom(mBottom);
8823            }
8824
8825            onSizeChanged(width, mBottom - mTop, width, oldHeight);
8826
8827            if (!matrixIsIdentity) {
8828                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8829                    // A change in dimension means an auto-centered pivot point changes, too
8830                    mTransformationInfo.mMatrixDirty = true;
8831                }
8832                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8833                invalidate(true);
8834            }
8835            mBackgroundSizeChanged = true;
8836            invalidateParentIfNeeded();
8837        }
8838    }
8839
8840    /**
8841     * Left position of this view relative to its parent.
8842     *
8843     * @return The left edge of this view, in pixels.
8844     */
8845    @ViewDebug.CapturedViewProperty
8846    public final int getLeft() {
8847        return mLeft;
8848    }
8849
8850    /**
8851     * Sets the left position of this view relative to its parent. This method is meant to be called
8852     * by the layout system and should not generally be called otherwise, because the property
8853     * may be changed at any time by the layout.
8854     *
8855     * @param left The bottom of this view, in pixels.
8856     */
8857    public final void setLeft(int left) {
8858        if (left != mLeft) {
8859            updateMatrix();
8860            final boolean matrixIsIdentity = mTransformationInfo == null
8861                    || mTransformationInfo.mMatrixIsIdentity;
8862            if (matrixIsIdentity) {
8863                if (mAttachInfo != null) {
8864                    int minLeft;
8865                    int xLoc;
8866                    if (left < mLeft) {
8867                        minLeft = left;
8868                        xLoc = left - mLeft;
8869                    } else {
8870                        minLeft = mLeft;
8871                        xLoc = 0;
8872                    }
8873                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
8874                }
8875            } else {
8876                // Double-invalidation is necessary to capture view's old and new areas
8877                invalidate(true);
8878            }
8879
8880            int oldWidth = mRight - mLeft;
8881            int height = mBottom - mTop;
8882
8883            mLeft = left;
8884            if (mDisplayList != null) {
8885                mDisplayList.setLeft(left);
8886            }
8887
8888            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8889
8890            if (!matrixIsIdentity) {
8891                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8892                    // A change in dimension means an auto-centered pivot point changes, too
8893                    mTransformationInfo.mMatrixDirty = true;
8894                }
8895                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8896                invalidate(true);
8897            }
8898            mBackgroundSizeChanged = true;
8899            invalidateParentIfNeeded();
8900        }
8901    }
8902
8903    /**
8904     * Right position of this view relative to its parent.
8905     *
8906     * @return The right edge of this view, in pixels.
8907     */
8908    @ViewDebug.CapturedViewProperty
8909    public final int getRight() {
8910        return mRight;
8911    }
8912
8913    /**
8914     * Sets the right position of this view relative to its parent. This method is meant to be called
8915     * by the layout system and should not generally be called otherwise, because the property
8916     * may be changed at any time by the layout.
8917     *
8918     * @param right The bottom of this view, in pixels.
8919     */
8920    public final void setRight(int right) {
8921        if (right != mRight) {
8922            updateMatrix();
8923            final boolean matrixIsIdentity = mTransformationInfo == null
8924                    || mTransformationInfo.mMatrixIsIdentity;
8925            if (matrixIsIdentity) {
8926                if (mAttachInfo != null) {
8927                    int maxRight;
8928                    if (right < mRight) {
8929                        maxRight = mRight;
8930                    } else {
8931                        maxRight = right;
8932                    }
8933                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
8934                }
8935            } else {
8936                // Double-invalidation is necessary to capture view's old and new areas
8937                invalidate(true);
8938            }
8939
8940            int oldWidth = mRight - mLeft;
8941            int height = mBottom - mTop;
8942
8943            mRight = right;
8944            if (mDisplayList != null) {
8945                mDisplayList.setRight(mRight);
8946            }
8947
8948            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8949
8950            if (!matrixIsIdentity) {
8951                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8952                    // A change in dimension means an auto-centered pivot point changes, too
8953                    mTransformationInfo.mMatrixDirty = true;
8954                }
8955                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8956                invalidate(true);
8957            }
8958            mBackgroundSizeChanged = true;
8959            invalidateParentIfNeeded();
8960        }
8961    }
8962
8963    /**
8964     * The visual x position of this view, in pixels. This is equivalent to the
8965     * {@link #setTranslationX(float) translationX} property plus the current
8966     * {@link #getLeft() left} property.
8967     *
8968     * @return The visual x position of this view, in pixels.
8969     */
8970    @ViewDebug.ExportedProperty(category = "drawing")
8971    public float getX() {
8972        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8973    }
8974
8975    /**
8976     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8977     * {@link #setTranslationX(float) translationX} property to be the difference between
8978     * the x value passed in and the current {@link #getLeft() left} property.
8979     *
8980     * @param x The visual x position of this view, in pixels.
8981     */
8982    public void setX(float x) {
8983        setTranslationX(x - mLeft);
8984    }
8985
8986    /**
8987     * The visual y position of this view, in pixels. This is equivalent to the
8988     * {@link #setTranslationY(float) translationY} property plus the current
8989     * {@link #getTop() top} property.
8990     *
8991     * @return The visual y position of this view, in pixels.
8992     */
8993    @ViewDebug.ExportedProperty(category = "drawing")
8994    public float getY() {
8995        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8996    }
8997
8998    /**
8999     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9000     * {@link #setTranslationY(float) translationY} property to be the difference between
9001     * the y value passed in and the current {@link #getTop() top} property.
9002     *
9003     * @param y The visual y position of this view, in pixels.
9004     */
9005    public void setY(float y) {
9006        setTranslationY(y - mTop);
9007    }
9008
9009
9010    /**
9011     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9012     * This position is post-layout, in addition to wherever the object's
9013     * layout placed it.
9014     *
9015     * @return The horizontal position of this view relative to its left position, in pixels.
9016     */
9017    @ViewDebug.ExportedProperty(category = "drawing")
9018    public float getTranslationX() {
9019        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9020    }
9021
9022    /**
9023     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9024     * This effectively positions the object post-layout, in addition to wherever the object's
9025     * layout placed it.
9026     *
9027     * @param translationX The horizontal position of this view relative to its left position,
9028     * in pixels.
9029     *
9030     * @attr ref android.R.styleable#View_translationX
9031     */
9032    public void setTranslationX(float translationX) {
9033        ensureTransformationInfo();
9034        final TransformationInfo info = mTransformationInfo;
9035        if (info.mTranslationX != translationX) {
9036            // Double-invalidation is necessary to capture view's old and new areas
9037            invalidateViewProperty(true, false);
9038            info.mTranslationX = translationX;
9039            info.mMatrixDirty = true;
9040            invalidateViewProperty(false, true);
9041            if (mDisplayList != null) {
9042                mDisplayList.setTranslationX(translationX);
9043            }
9044        }
9045    }
9046
9047    /**
9048     * The horizontal location of this view relative to its {@link #getTop() top} position.
9049     * This position is post-layout, in addition to wherever the object's
9050     * layout placed it.
9051     *
9052     * @return The vertical position of this view relative to its top position,
9053     * in pixels.
9054     */
9055    @ViewDebug.ExportedProperty(category = "drawing")
9056    public float getTranslationY() {
9057        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9058    }
9059
9060    /**
9061     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9062     * This effectively positions the object post-layout, in addition to wherever the object's
9063     * layout placed it.
9064     *
9065     * @param translationY The vertical position of this view relative to its top position,
9066     * in pixels.
9067     *
9068     * @attr ref android.R.styleable#View_translationY
9069     */
9070    public void setTranslationY(float translationY) {
9071        ensureTransformationInfo();
9072        final TransformationInfo info = mTransformationInfo;
9073        if (info.mTranslationY != translationY) {
9074            invalidateViewProperty(true, false);
9075            info.mTranslationY = translationY;
9076            info.mMatrixDirty = true;
9077            invalidateViewProperty(false, true);
9078            if (mDisplayList != null) {
9079                mDisplayList.setTranslationY(translationY);
9080            }
9081        }
9082    }
9083
9084    /**
9085     * Hit rectangle in parent's coordinates
9086     *
9087     * @param outRect The hit rectangle of the view.
9088     */
9089    public void getHitRect(Rect outRect) {
9090        updateMatrix();
9091        final TransformationInfo info = mTransformationInfo;
9092        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9093            outRect.set(mLeft, mTop, mRight, mBottom);
9094        } else {
9095            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9096            tmpRect.set(-info.mPivotX, -info.mPivotY,
9097                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9098            info.mMatrix.mapRect(tmpRect);
9099            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9100                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9101        }
9102    }
9103
9104    /**
9105     * Determines whether the given point, in local coordinates is inside the view.
9106     */
9107    /*package*/ final boolean pointInView(float localX, float localY) {
9108        return localX >= 0 && localX < (mRight - mLeft)
9109                && localY >= 0 && localY < (mBottom - mTop);
9110    }
9111
9112    /**
9113     * Utility method to determine whether the given point, in local coordinates,
9114     * is inside the view, where the area of the view is expanded by the slop factor.
9115     * This method is called while processing touch-move events to determine if the event
9116     * is still within the view.
9117     */
9118    private boolean pointInView(float localX, float localY, float slop) {
9119        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9120                localY < ((mBottom - mTop) + slop);
9121    }
9122
9123    /**
9124     * When a view has focus and the user navigates away from it, the next view is searched for
9125     * starting from the rectangle filled in by this method.
9126     *
9127     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9128     * of the view.  However, if your view maintains some idea of internal selection,
9129     * such as a cursor, or a selected row or column, you should override this method and
9130     * fill in a more specific rectangle.
9131     *
9132     * @param r The rectangle to fill in, in this view's coordinates.
9133     */
9134    public void getFocusedRect(Rect r) {
9135        getDrawingRect(r);
9136    }
9137
9138    /**
9139     * If some part of this view is not clipped by any of its parents, then
9140     * return that area in r in global (root) coordinates. To convert r to local
9141     * coordinates (without taking possible View rotations into account), offset
9142     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9143     * If the view is completely clipped or translated out, return false.
9144     *
9145     * @param r If true is returned, r holds the global coordinates of the
9146     *        visible portion of this view.
9147     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9148     *        between this view and its root. globalOffet may be null.
9149     * @return true if r is non-empty (i.e. part of the view is visible at the
9150     *         root level.
9151     */
9152    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9153        int width = mRight - mLeft;
9154        int height = mBottom - mTop;
9155        if (width > 0 && height > 0) {
9156            r.set(0, 0, width, height);
9157            if (globalOffset != null) {
9158                globalOffset.set(-mScrollX, -mScrollY);
9159            }
9160            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9161        }
9162        return false;
9163    }
9164
9165    public final boolean getGlobalVisibleRect(Rect r) {
9166        return getGlobalVisibleRect(r, null);
9167    }
9168
9169    public final boolean getLocalVisibleRect(Rect r) {
9170        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9171        if (getGlobalVisibleRect(r, offset)) {
9172            r.offset(-offset.x, -offset.y); // make r local
9173            return true;
9174        }
9175        return false;
9176    }
9177
9178    /**
9179     * Offset this view's vertical location by the specified number of pixels.
9180     *
9181     * @param offset the number of pixels to offset the view by
9182     */
9183    public void offsetTopAndBottom(int offset) {
9184        if (offset != 0) {
9185            updateMatrix();
9186            final boolean matrixIsIdentity = mTransformationInfo == null
9187                    || mTransformationInfo.mMatrixIsIdentity;
9188            if (matrixIsIdentity) {
9189                if (mDisplayList != null) {
9190                    invalidateViewProperty(false, false);
9191                } else {
9192                    final ViewParent p = mParent;
9193                    if (p != null && mAttachInfo != null) {
9194                        final Rect r = mAttachInfo.mTmpInvalRect;
9195                        int minTop;
9196                        int maxBottom;
9197                        int yLoc;
9198                        if (offset < 0) {
9199                            minTop = mTop + offset;
9200                            maxBottom = mBottom;
9201                            yLoc = offset;
9202                        } else {
9203                            minTop = mTop;
9204                            maxBottom = mBottom + offset;
9205                            yLoc = 0;
9206                        }
9207                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9208                        p.invalidateChild(this, r);
9209                    }
9210                }
9211            } else {
9212                invalidateViewProperty(false, false);
9213            }
9214
9215            mTop += offset;
9216            mBottom += offset;
9217            if (mDisplayList != null) {
9218                mDisplayList.offsetTopBottom(offset);
9219                invalidateViewProperty(false, false);
9220            } else {
9221                if (!matrixIsIdentity) {
9222                    invalidateViewProperty(false, true);
9223                }
9224                invalidateParentIfNeeded();
9225            }
9226        }
9227    }
9228
9229    /**
9230     * Offset this view's horizontal location by the specified amount of pixels.
9231     *
9232     * @param offset the numer of pixels to offset the view by
9233     */
9234    public void offsetLeftAndRight(int offset) {
9235        if (offset != 0) {
9236            updateMatrix();
9237            final boolean matrixIsIdentity = mTransformationInfo == null
9238                    || mTransformationInfo.mMatrixIsIdentity;
9239            if (matrixIsIdentity) {
9240                if (mDisplayList != null) {
9241                    invalidateViewProperty(false, false);
9242                } else {
9243                    final ViewParent p = mParent;
9244                    if (p != null && mAttachInfo != null) {
9245                        final Rect r = mAttachInfo.mTmpInvalRect;
9246                        int minLeft;
9247                        int maxRight;
9248                        if (offset < 0) {
9249                            minLeft = mLeft + offset;
9250                            maxRight = mRight;
9251                        } else {
9252                            minLeft = mLeft;
9253                            maxRight = mRight + offset;
9254                        }
9255                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9256                        p.invalidateChild(this, r);
9257                    }
9258                }
9259            } else {
9260                invalidateViewProperty(false, false);
9261            }
9262
9263            mLeft += offset;
9264            mRight += offset;
9265            if (mDisplayList != null) {
9266                mDisplayList.offsetLeftRight(offset);
9267                invalidateViewProperty(false, false);
9268            } else {
9269                if (!matrixIsIdentity) {
9270                    invalidateViewProperty(false, true);
9271                }
9272                invalidateParentIfNeeded();
9273            }
9274        }
9275    }
9276
9277    /**
9278     * Get the LayoutParams associated with this view. All views should have
9279     * layout parameters. These supply parameters to the <i>parent</i> of this
9280     * view specifying how it should be arranged. There are many subclasses of
9281     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9282     * of ViewGroup that are responsible for arranging their children.
9283     *
9284     * This method may return null if this View is not attached to a parent
9285     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9286     * was not invoked successfully. When a View is attached to a parent
9287     * ViewGroup, this method must not return null.
9288     *
9289     * @return The LayoutParams associated with this view, or null if no
9290     *         parameters have been set yet
9291     */
9292    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9293    public ViewGroup.LayoutParams getLayoutParams() {
9294        return mLayoutParams;
9295    }
9296
9297    /**
9298     * Set the layout parameters associated with this view. These supply
9299     * parameters to the <i>parent</i> of this view specifying how it should be
9300     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9301     * correspond to the different subclasses of ViewGroup that are responsible
9302     * for arranging their children.
9303     *
9304     * @param params The layout parameters for this view, cannot be null
9305     */
9306    public void setLayoutParams(ViewGroup.LayoutParams params) {
9307        if (params == null) {
9308            throw new NullPointerException("Layout parameters cannot be null");
9309        }
9310        mLayoutParams = params;
9311        if (mParent instanceof ViewGroup) {
9312            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9313        }
9314        requestLayout();
9315    }
9316
9317    /**
9318     * Set the scrolled position of your view. This will cause a call to
9319     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9320     * invalidated.
9321     * @param x the x position to scroll to
9322     * @param y the y position to scroll to
9323     */
9324    public void scrollTo(int x, int y) {
9325        if (mScrollX != x || mScrollY != y) {
9326            int oldX = mScrollX;
9327            int oldY = mScrollY;
9328            mScrollX = x;
9329            mScrollY = y;
9330            invalidateParentCaches();
9331            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9332            if (!awakenScrollBars()) {
9333                postInvalidateOnAnimation();
9334            }
9335        }
9336    }
9337
9338    /**
9339     * Move the scrolled position of your view. This will cause a call to
9340     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9341     * invalidated.
9342     * @param x the amount of pixels to scroll by horizontally
9343     * @param y the amount of pixels to scroll by vertically
9344     */
9345    public void scrollBy(int x, int y) {
9346        scrollTo(mScrollX + x, mScrollY + y);
9347    }
9348
9349    /**
9350     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9351     * animation to fade the scrollbars out after a default delay. If a subclass
9352     * provides animated scrolling, the start delay should equal the duration
9353     * of the scrolling animation.</p>
9354     *
9355     * <p>The animation starts only if at least one of the scrollbars is
9356     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9357     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9358     * this method returns true, and false otherwise. If the animation is
9359     * started, this method calls {@link #invalidate()}; in that case the
9360     * caller should not call {@link #invalidate()}.</p>
9361     *
9362     * <p>This method should be invoked every time a subclass directly updates
9363     * the scroll parameters.</p>
9364     *
9365     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9366     * and {@link #scrollTo(int, int)}.</p>
9367     *
9368     * @return true if the animation is played, false otherwise
9369     *
9370     * @see #awakenScrollBars(int)
9371     * @see #scrollBy(int, int)
9372     * @see #scrollTo(int, int)
9373     * @see #isHorizontalScrollBarEnabled()
9374     * @see #isVerticalScrollBarEnabled()
9375     * @see #setHorizontalScrollBarEnabled(boolean)
9376     * @see #setVerticalScrollBarEnabled(boolean)
9377     */
9378    protected boolean awakenScrollBars() {
9379        return mScrollCache != null &&
9380                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9381    }
9382
9383    /**
9384     * Trigger the scrollbars to draw.
9385     * This method differs from awakenScrollBars() only in its default duration.
9386     * initialAwakenScrollBars() will show the scroll bars for longer than
9387     * usual to give the user more of a chance to notice them.
9388     *
9389     * @return true if the animation is played, false otherwise.
9390     */
9391    private boolean initialAwakenScrollBars() {
9392        return mScrollCache != null &&
9393                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9394    }
9395
9396    /**
9397     * <p>
9398     * Trigger the scrollbars to draw. When invoked this method starts an
9399     * animation to fade the scrollbars out after a fixed delay. If a subclass
9400     * provides animated scrolling, the start delay should equal the duration of
9401     * the scrolling animation.
9402     * </p>
9403     *
9404     * <p>
9405     * The animation starts only if at least one of the scrollbars is enabled,
9406     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9407     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9408     * this method returns true, and false otherwise. If the animation is
9409     * started, this method calls {@link #invalidate()}; in that case the caller
9410     * should not call {@link #invalidate()}.
9411     * </p>
9412     *
9413     * <p>
9414     * This method should be invoked everytime a subclass directly updates the
9415     * scroll parameters.
9416     * </p>
9417     *
9418     * @param startDelay the delay, in milliseconds, after which the animation
9419     *        should start; when the delay is 0, the animation starts
9420     *        immediately
9421     * @return true if the animation is played, false otherwise
9422     *
9423     * @see #scrollBy(int, int)
9424     * @see #scrollTo(int, int)
9425     * @see #isHorizontalScrollBarEnabled()
9426     * @see #isVerticalScrollBarEnabled()
9427     * @see #setHorizontalScrollBarEnabled(boolean)
9428     * @see #setVerticalScrollBarEnabled(boolean)
9429     */
9430    protected boolean awakenScrollBars(int startDelay) {
9431        return awakenScrollBars(startDelay, true);
9432    }
9433
9434    /**
9435     * <p>
9436     * Trigger the scrollbars to draw. When invoked this method starts an
9437     * animation to fade the scrollbars out after a fixed delay. If a subclass
9438     * provides animated scrolling, the start delay should equal the duration of
9439     * the scrolling animation.
9440     * </p>
9441     *
9442     * <p>
9443     * The animation starts only if at least one of the scrollbars is enabled,
9444     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9445     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9446     * this method returns true, and false otherwise. If the animation is
9447     * started, this method calls {@link #invalidate()} if the invalidate parameter
9448     * is set to true; in that case the caller
9449     * should not call {@link #invalidate()}.
9450     * </p>
9451     *
9452     * <p>
9453     * This method should be invoked everytime a subclass directly updates the
9454     * scroll parameters.
9455     * </p>
9456     *
9457     * @param startDelay the delay, in milliseconds, after which the animation
9458     *        should start; when the delay is 0, the animation starts
9459     *        immediately
9460     *
9461     * @param invalidate Wheter this method should call invalidate
9462     *
9463     * @return true if the animation is played, false otherwise
9464     *
9465     * @see #scrollBy(int, int)
9466     * @see #scrollTo(int, int)
9467     * @see #isHorizontalScrollBarEnabled()
9468     * @see #isVerticalScrollBarEnabled()
9469     * @see #setHorizontalScrollBarEnabled(boolean)
9470     * @see #setVerticalScrollBarEnabled(boolean)
9471     */
9472    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9473        final ScrollabilityCache scrollCache = mScrollCache;
9474
9475        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9476            return false;
9477        }
9478
9479        if (scrollCache.scrollBar == null) {
9480            scrollCache.scrollBar = new ScrollBarDrawable();
9481        }
9482
9483        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9484
9485            if (invalidate) {
9486                // Invalidate to show the scrollbars
9487                postInvalidateOnAnimation();
9488            }
9489
9490            if (scrollCache.state == ScrollabilityCache.OFF) {
9491                // FIXME: this is copied from WindowManagerService.
9492                // We should get this value from the system when it
9493                // is possible to do so.
9494                final int KEY_REPEAT_FIRST_DELAY = 750;
9495                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9496            }
9497
9498            // Tell mScrollCache when we should start fading. This may
9499            // extend the fade start time if one was already scheduled
9500            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9501            scrollCache.fadeStartTime = fadeStartTime;
9502            scrollCache.state = ScrollabilityCache.ON;
9503
9504            // Schedule our fader to run, unscheduling any old ones first
9505            if (mAttachInfo != null) {
9506                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9507                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9508            }
9509
9510            return true;
9511        }
9512
9513        return false;
9514    }
9515
9516    /**
9517     * Do not invalidate views which are not visible and which are not running an animation. They
9518     * will not get drawn and they should not set dirty flags as if they will be drawn
9519     */
9520    private boolean skipInvalidate() {
9521        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9522                (!(mParent instanceof ViewGroup) ||
9523                        !((ViewGroup) mParent).isViewTransitioning(this));
9524    }
9525    /**
9526     * Mark the area defined by dirty as needing to be drawn. If the view is
9527     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9528     * in the future. This must be called from a UI thread. To call from a non-UI
9529     * thread, call {@link #postInvalidate()}.
9530     *
9531     * WARNING: This method is destructive to dirty.
9532     * @param dirty the rectangle representing the bounds of the dirty region
9533     */
9534    public void invalidate(Rect dirty) {
9535        if (ViewDebug.TRACE_HIERARCHY) {
9536            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9537        }
9538
9539        if (skipInvalidate()) {
9540            return;
9541        }
9542        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9543                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9544                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9545            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9546            mPrivateFlags |= INVALIDATED;
9547            mPrivateFlags |= DIRTY;
9548            final ViewParent p = mParent;
9549            final AttachInfo ai = mAttachInfo;
9550            //noinspection PointlessBooleanExpression,ConstantConditions
9551            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9552                if (p != null && ai != null && ai.mHardwareAccelerated) {
9553                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9554                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9555                    p.invalidateChild(this, null);
9556                    return;
9557                }
9558            }
9559            if (p != null && ai != null) {
9560                final int scrollX = mScrollX;
9561                final int scrollY = mScrollY;
9562                final Rect r = ai.mTmpInvalRect;
9563                r.set(dirty.left - scrollX, dirty.top - scrollY,
9564                        dirty.right - scrollX, dirty.bottom - scrollY);
9565                mParent.invalidateChild(this, r);
9566            }
9567        }
9568    }
9569
9570    /**
9571     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9572     * The coordinates of the dirty rect are relative to the view.
9573     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9574     * will be called at some point in the future. This must be called from
9575     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9576     * @param l the left position of the dirty region
9577     * @param t the top position of the dirty region
9578     * @param r the right position of the dirty region
9579     * @param b the bottom position of the dirty region
9580     */
9581    public void invalidate(int l, int t, int r, int b) {
9582        if (ViewDebug.TRACE_HIERARCHY) {
9583            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9584        }
9585
9586        if (skipInvalidate()) {
9587            return;
9588        }
9589        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9590                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9591                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9592            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9593            mPrivateFlags |= INVALIDATED;
9594            mPrivateFlags |= DIRTY;
9595            final ViewParent p = mParent;
9596            final AttachInfo ai = mAttachInfo;
9597            //noinspection PointlessBooleanExpression,ConstantConditions
9598            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9599                if (p != null && ai != null && ai.mHardwareAccelerated) {
9600                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9601                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9602                    p.invalidateChild(this, null);
9603                    return;
9604                }
9605            }
9606            if (p != null && ai != null && l < r && t < b) {
9607                final int scrollX = mScrollX;
9608                final int scrollY = mScrollY;
9609                final Rect tmpr = ai.mTmpInvalRect;
9610                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9611                p.invalidateChild(this, tmpr);
9612            }
9613        }
9614    }
9615
9616    /**
9617     * Invalidate the whole view. If the view is visible,
9618     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9619     * the future. This must be called from a UI thread. To call from a non-UI thread,
9620     * call {@link #postInvalidate()}.
9621     */
9622    public void invalidate() {
9623        invalidate(true);
9624    }
9625
9626    /**
9627     * This is where the invalidate() work actually happens. A full invalidate()
9628     * causes the drawing cache to be invalidated, but this function can be called with
9629     * invalidateCache set to false to skip that invalidation step for cases that do not
9630     * need it (for example, a component that remains at the same dimensions with the same
9631     * content).
9632     *
9633     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9634     * well. This is usually true for a full invalidate, but may be set to false if the
9635     * View's contents or dimensions have not changed.
9636     */
9637    void invalidate(boolean invalidateCache) {
9638        if (ViewDebug.TRACE_HIERARCHY) {
9639            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
9640        }
9641
9642        if (skipInvalidate()) {
9643            return;
9644        }
9645        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9646                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9647                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9648            mLastIsOpaque = isOpaque();
9649            mPrivateFlags &= ~DRAWN;
9650            mPrivateFlags |= DIRTY;
9651            if (invalidateCache) {
9652                mPrivateFlags |= INVALIDATED;
9653                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9654            }
9655            final AttachInfo ai = mAttachInfo;
9656            final ViewParent p = mParent;
9657            //noinspection PointlessBooleanExpression,ConstantConditions
9658            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9659                if (p != null && ai != null && ai.mHardwareAccelerated) {
9660                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9661                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9662                    p.invalidateChild(this, null);
9663                    return;
9664                }
9665            }
9666
9667            if (p != null && ai != null) {
9668                final Rect r = ai.mTmpInvalRect;
9669                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9670                // Don't call invalidate -- we don't want to internally scroll
9671                // our own bounds
9672                p.invalidateChild(this, r);
9673            }
9674        }
9675    }
9676
9677    /**
9678     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
9679     * set any flags or handle all of the cases handled by the default invalidation methods.
9680     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
9681     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
9682     * walk up the hierarchy, transforming the dirty rect as necessary.
9683     *
9684     * The method also handles normal invalidation logic if display list properties are not
9685     * being used in this view. The invalidateParent and forceRedraw flags are used by that
9686     * backup approach, to handle these cases used in the various property-setting methods.
9687     *
9688     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
9689     * are not being used in this view
9690     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
9691     * list properties are not being used in this view
9692     */
9693    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
9694        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
9695            if (invalidateParent) {
9696                invalidateParentCaches();
9697            }
9698            if (forceRedraw) {
9699                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9700            }
9701            invalidate(false);
9702        } else {
9703            final AttachInfo ai = mAttachInfo;
9704            final ViewParent p = mParent;
9705            if (p != null && ai != null) {
9706                final Rect r = ai.mTmpInvalRect;
9707                r.set(0, 0, mRight - mLeft, mBottom - mTop);
9708                if (mParent instanceof ViewGroup) {
9709                    ((ViewGroup) mParent).invalidateChildFast(this, r);
9710                } else {
9711                    mParent.invalidateChild(this, r);
9712                }
9713            }
9714        }
9715    }
9716
9717    /**
9718     * Utility method to transform a given Rect by the current matrix of this view.
9719     */
9720    void transformRect(final Rect rect) {
9721        if (!getMatrix().isIdentity()) {
9722            RectF boundingRect = mAttachInfo.mTmpTransformRect;
9723            boundingRect.set(rect);
9724            getMatrix().mapRect(boundingRect);
9725            rect.set((int) (boundingRect.left - 0.5f),
9726                    (int) (boundingRect.top - 0.5f),
9727                    (int) (boundingRect.right + 0.5f),
9728                    (int) (boundingRect.bottom + 0.5f));
9729        }
9730    }
9731
9732    /**
9733     * Used to indicate that the parent of this view should clear its caches. This functionality
9734     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9735     * which is necessary when various parent-managed properties of the view change, such as
9736     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
9737     * clears the parent caches and does not causes an invalidate event.
9738     *
9739     * @hide
9740     */
9741    protected void invalidateParentCaches() {
9742        if (mParent instanceof View) {
9743            ((View) mParent).mPrivateFlags |= INVALIDATED;
9744        }
9745    }
9746
9747    /**
9748     * Used to indicate that the parent of this view should be invalidated. This functionality
9749     * is used to force the parent to rebuild its display list (when hardware-accelerated),
9750     * which is necessary when various parent-managed properties of the view change, such as
9751     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
9752     * an invalidation event to the parent.
9753     *
9754     * @hide
9755     */
9756    protected void invalidateParentIfNeeded() {
9757        if (isHardwareAccelerated() && mParent instanceof View) {
9758            ((View) mParent).invalidate(true);
9759        }
9760    }
9761
9762    /**
9763     * Indicates whether this View is opaque. An opaque View guarantees that it will
9764     * draw all the pixels overlapping its bounds using a fully opaque color.
9765     *
9766     * Subclasses of View should override this method whenever possible to indicate
9767     * whether an instance is opaque. Opaque Views are treated in a special way by
9768     * the View hierarchy, possibly allowing it to perform optimizations during
9769     * invalidate/draw passes.
9770     *
9771     * @return True if this View is guaranteed to be fully opaque, false otherwise.
9772     */
9773    @ViewDebug.ExportedProperty(category = "drawing")
9774    public boolean isOpaque() {
9775        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
9776                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
9777                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
9778    }
9779
9780    /**
9781     * @hide
9782     */
9783    protected void computeOpaqueFlags() {
9784        // Opaque if:
9785        //   - Has a background
9786        //   - Background is opaque
9787        //   - Doesn't have scrollbars or scrollbars are inside overlay
9788
9789        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
9790            mPrivateFlags |= OPAQUE_BACKGROUND;
9791        } else {
9792            mPrivateFlags &= ~OPAQUE_BACKGROUND;
9793        }
9794
9795        final int flags = mViewFlags;
9796        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
9797                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
9798            mPrivateFlags |= OPAQUE_SCROLLBARS;
9799        } else {
9800            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
9801        }
9802    }
9803
9804    /**
9805     * @hide
9806     */
9807    protected boolean hasOpaqueScrollbars() {
9808        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
9809    }
9810
9811    /**
9812     * @return A handler associated with the thread running the View. This
9813     * handler can be used to pump events in the UI events queue.
9814     */
9815    public Handler getHandler() {
9816        if (mAttachInfo != null) {
9817            return mAttachInfo.mHandler;
9818        }
9819        return null;
9820    }
9821
9822    /**
9823     * Gets the view root associated with the View.
9824     * @return The view root, or null if none.
9825     * @hide
9826     */
9827    public ViewRootImpl getViewRootImpl() {
9828        if (mAttachInfo != null) {
9829            return mAttachInfo.mViewRootImpl;
9830        }
9831        return null;
9832    }
9833
9834    /**
9835     * <p>Causes the Runnable to be added to the message queue.
9836     * The runnable will be run on the user interface thread.</p>
9837     *
9838     * <p>This method can be invoked from outside of the UI thread
9839     * only when this View is attached to a window.</p>
9840     *
9841     * @param action The Runnable that will be executed.
9842     *
9843     * @return Returns true if the Runnable was successfully placed in to the
9844     *         message queue.  Returns false on failure, usually because the
9845     *         looper processing the message queue is exiting.
9846     *
9847     * @see #postDelayed
9848     * @see #removeCallbacks
9849     */
9850    public boolean post(Runnable action) {
9851        final AttachInfo attachInfo = mAttachInfo;
9852        if (attachInfo != null) {
9853            return attachInfo.mHandler.post(action);
9854        }
9855        // Assume that post will succeed later
9856        ViewRootImpl.getRunQueue().post(action);
9857        return true;
9858    }
9859
9860    /**
9861     * <p>Causes the Runnable to be added to the message queue, to be run
9862     * after the specified amount of time elapses.
9863     * The runnable will be run on the user interface thread.</p>
9864     *
9865     * <p>This method can be invoked from outside of the UI thread
9866     * only when this View is attached to a window.</p>
9867     *
9868     * @param action The Runnable that will be executed.
9869     * @param delayMillis The delay (in milliseconds) until the Runnable
9870     *        will be executed.
9871     *
9872     * @return true if the Runnable was successfully placed in to the
9873     *         message queue.  Returns false on failure, usually because the
9874     *         looper processing the message queue is exiting.  Note that a
9875     *         result of true does not mean the Runnable will be processed --
9876     *         if the looper is quit before the delivery time of the message
9877     *         occurs then the message will be dropped.
9878     *
9879     * @see #post
9880     * @see #removeCallbacks
9881     */
9882    public boolean postDelayed(Runnable action, long delayMillis) {
9883        final AttachInfo attachInfo = mAttachInfo;
9884        if (attachInfo != null) {
9885            return attachInfo.mHandler.postDelayed(action, delayMillis);
9886        }
9887        // Assume that post will succeed later
9888        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9889        return true;
9890    }
9891
9892    /**
9893     * <p>Causes the Runnable to execute on the next animation time step.
9894     * The runnable will be run on the user interface thread.</p>
9895     *
9896     * <p>This method can be invoked from outside of the UI thread
9897     * only when this View is attached to a window.</p>
9898     *
9899     * @param action The Runnable that will be executed.
9900     *
9901     * @see #postOnAnimationDelayed
9902     * @see #removeCallbacks
9903     */
9904    public void postOnAnimation(Runnable action) {
9905        final AttachInfo attachInfo = mAttachInfo;
9906        if (attachInfo != null) {
9907            attachInfo.mViewRootImpl.mChoreographer.postCallback(
9908                    Choreographer.CALLBACK_ANIMATION, action, null);
9909        } else {
9910            // Assume that post will succeed later
9911            ViewRootImpl.getRunQueue().post(action);
9912        }
9913    }
9914
9915    /**
9916     * <p>Causes the Runnable to execute on the next animation time step,
9917     * after the specified amount of time elapses.
9918     * The runnable will be run on the user interface thread.</p>
9919     *
9920     * <p>This method can be invoked from outside of the UI thread
9921     * only when this View is attached to a window.</p>
9922     *
9923     * @param action The Runnable that will be executed.
9924     * @param delayMillis The delay (in milliseconds) until the Runnable
9925     *        will be executed.
9926     *
9927     * @see #postOnAnimation
9928     * @see #removeCallbacks
9929     */
9930    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
9931        final AttachInfo attachInfo = mAttachInfo;
9932        if (attachInfo != null) {
9933            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
9934                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
9935        } else {
9936            // Assume that post will succeed later
9937            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
9938        }
9939    }
9940
9941    /**
9942     * <p>Removes the specified Runnable from the message queue.</p>
9943     *
9944     * <p>This method can be invoked from outside of the UI thread
9945     * only when this View is attached to a window.</p>
9946     *
9947     * @param action The Runnable to remove from the message handling queue
9948     *
9949     * @return true if this view could ask the Handler to remove the Runnable,
9950     *         false otherwise. When the returned value is true, the Runnable
9951     *         may or may not have been actually removed from the message queue
9952     *         (for instance, if the Runnable was not in the queue already.)
9953     *
9954     * @see #post
9955     * @see #postDelayed
9956     * @see #postOnAnimation
9957     * @see #postOnAnimationDelayed
9958     */
9959    public boolean removeCallbacks(Runnable action) {
9960        if (action != null) {
9961            final AttachInfo attachInfo = mAttachInfo;
9962            if (attachInfo != null) {
9963                attachInfo.mHandler.removeCallbacks(action);
9964                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
9965                        Choreographer.CALLBACK_ANIMATION, action, null);
9966            } else {
9967                // Assume that post will succeed later
9968                ViewRootImpl.getRunQueue().removeCallbacks(action);
9969            }
9970        }
9971        return true;
9972    }
9973
9974    /**
9975     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
9976     * Use this to invalidate the View from a non-UI thread.</p>
9977     *
9978     * <p>This method can be invoked from outside of the UI thread
9979     * only when this View is attached to a window.</p>
9980     *
9981     * @see #invalidate()
9982     * @see #postInvalidateDelayed(long)
9983     */
9984    public void postInvalidate() {
9985        postInvalidateDelayed(0);
9986    }
9987
9988    /**
9989     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9990     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
9991     *
9992     * <p>This method can be invoked from outside of the UI thread
9993     * only when this View is attached to a window.</p>
9994     *
9995     * @param left The left coordinate of the rectangle to invalidate.
9996     * @param top The top coordinate of the rectangle to invalidate.
9997     * @param right The right coordinate of the rectangle to invalidate.
9998     * @param bottom The bottom coordinate of the rectangle to invalidate.
9999     *
10000     * @see #invalidate(int, int, int, int)
10001     * @see #invalidate(Rect)
10002     * @see #postInvalidateDelayed(long, int, int, int, int)
10003     */
10004    public void postInvalidate(int left, int top, int right, int bottom) {
10005        postInvalidateDelayed(0, left, top, right, bottom);
10006    }
10007
10008    /**
10009     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10010     * loop. Waits for the specified amount of time.</p>
10011     *
10012     * <p>This method can be invoked from outside of the UI thread
10013     * only when this View is attached to a window.</p>
10014     *
10015     * @param delayMilliseconds the duration in milliseconds to delay the
10016     *         invalidation by
10017     *
10018     * @see #invalidate()
10019     * @see #postInvalidate()
10020     */
10021    public void postInvalidateDelayed(long delayMilliseconds) {
10022        // We try only with the AttachInfo because there's no point in invalidating
10023        // if we are not attached to our window
10024        final AttachInfo attachInfo = mAttachInfo;
10025        if (attachInfo != null) {
10026            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10027        }
10028    }
10029
10030    /**
10031     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10032     * through the event loop. Waits for the specified amount of time.</p>
10033     *
10034     * <p>This method can be invoked from outside of the UI thread
10035     * only when this View is attached to a window.</p>
10036     *
10037     * @param delayMilliseconds the duration in milliseconds to delay the
10038     *         invalidation by
10039     * @param left The left coordinate of the rectangle to invalidate.
10040     * @param top The top coordinate of the rectangle to invalidate.
10041     * @param right The right coordinate of the rectangle to invalidate.
10042     * @param bottom The bottom coordinate of the rectangle to invalidate.
10043     *
10044     * @see #invalidate(int, int, int, int)
10045     * @see #invalidate(Rect)
10046     * @see #postInvalidate(int, int, int, int)
10047     */
10048    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10049            int right, int bottom) {
10050
10051        // We try only with the AttachInfo because there's no point in invalidating
10052        // if we are not attached to our window
10053        final AttachInfo attachInfo = mAttachInfo;
10054        if (attachInfo != null) {
10055            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10056            info.target = this;
10057            info.left = left;
10058            info.top = top;
10059            info.right = right;
10060            info.bottom = bottom;
10061
10062            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10063        }
10064    }
10065
10066    /**
10067     * <p>Cause an invalidate to happen on the next animation time step, typically the
10068     * next display frame.</p>
10069     *
10070     * <p>This method can be invoked from outside of the UI thread
10071     * only when this View is attached to a window.</p>
10072     *
10073     * @see #invalidate()
10074     */
10075    public void postInvalidateOnAnimation() {
10076        // We try only with the AttachInfo because there's no point in invalidating
10077        // if we are not attached to our window
10078        final AttachInfo attachInfo = mAttachInfo;
10079        if (attachInfo != null) {
10080            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10081        }
10082    }
10083
10084    /**
10085     * <p>Cause an invalidate of the specified area to happen on the next animation
10086     * time step, typically the next display frame.</p>
10087     *
10088     * <p>This method can be invoked from outside of the UI thread
10089     * only when this View is attached to a window.</p>
10090     *
10091     * @param left The left coordinate of the rectangle to invalidate.
10092     * @param top The top coordinate of the rectangle to invalidate.
10093     * @param right The right coordinate of the rectangle to invalidate.
10094     * @param bottom The bottom coordinate of the rectangle to invalidate.
10095     *
10096     * @see #invalidate(int, int, int, int)
10097     * @see #invalidate(Rect)
10098     */
10099    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10100        // We try only with the AttachInfo because there's no point in invalidating
10101        // if we are not attached to our window
10102        final AttachInfo attachInfo = mAttachInfo;
10103        if (attachInfo != null) {
10104            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10105            info.target = this;
10106            info.left = left;
10107            info.top = top;
10108            info.right = right;
10109            info.bottom = bottom;
10110
10111            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10112        }
10113    }
10114
10115    /**
10116     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10117     * This event is sent at most once every
10118     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10119     */
10120    private void postSendViewScrolledAccessibilityEventCallback() {
10121        if (mSendViewScrolledAccessibilityEvent == null) {
10122            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10123        }
10124        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10125            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10126            postDelayed(mSendViewScrolledAccessibilityEvent,
10127                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10128        }
10129    }
10130
10131    /**
10132     * Called by a parent to request that a child update its values for mScrollX
10133     * and mScrollY if necessary. This will typically be done if the child is
10134     * animating a scroll using a {@link android.widget.Scroller Scroller}
10135     * object.
10136     */
10137    public void computeScroll() {
10138    }
10139
10140    /**
10141     * <p>Indicate whether the horizontal edges are faded when the view is
10142     * scrolled horizontally.</p>
10143     *
10144     * @return true if the horizontal edges should are faded on scroll, false
10145     *         otherwise
10146     *
10147     * @see #setHorizontalFadingEdgeEnabled(boolean)
10148     *
10149     * @attr ref android.R.styleable#View_requiresFadingEdge
10150     */
10151    public boolean isHorizontalFadingEdgeEnabled() {
10152        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10153    }
10154
10155    /**
10156     * <p>Define whether the horizontal edges should be faded when this view
10157     * is scrolled horizontally.</p>
10158     *
10159     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10160     *                                    be faded when the view is scrolled
10161     *                                    horizontally
10162     *
10163     * @see #isHorizontalFadingEdgeEnabled()
10164     *
10165     * @attr ref android.R.styleable#View_requiresFadingEdge
10166     */
10167    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10168        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10169            if (horizontalFadingEdgeEnabled) {
10170                initScrollCache();
10171            }
10172
10173            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10174        }
10175    }
10176
10177    /**
10178     * <p>Indicate whether the vertical edges are faded when the view is
10179     * scrolled horizontally.</p>
10180     *
10181     * @return true if the vertical edges should are faded on scroll, false
10182     *         otherwise
10183     *
10184     * @see #setVerticalFadingEdgeEnabled(boolean)
10185     *
10186     * @attr ref android.R.styleable#View_requiresFadingEdge
10187     */
10188    public boolean isVerticalFadingEdgeEnabled() {
10189        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10190    }
10191
10192    /**
10193     * <p>Define whether the vertical edges should be faded when this view
10194     * is scrolled vertically.</p>
10195     *
10196     * @param verticalFadingEdgeEnabled true if the vertical edges should
10197     *                                  be faded when the view is scrolled
10198     *                                  vertically
10199     *
10200     * @see #isVerticalFadingEdgeEnabled()
10201     *
10202     * @attr ref android.R.styleable#View_requiresFadingEdge
10203     */
10204    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10205        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10206            if (verticalFadingEdgeEnabled) {
10207                initScrollCache();
10208            }
10209
10210            mViewFlags ^= FADING_EDGE_VERTICAL;
10211        }
10212    }
10213
10214    /**
10215     * Returns the strength, or intensity, of the top faded edge. The strength is
10216     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10217     * returns 0.0 or 1.0 but no value in between.
10218     *
10219     * Subclasses should override this method to provide a smoother fade transition
10220     * when scrolling occurs.
10221     *
10222     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10223     */
10224    protected float getTopFadingEdgeStrength() {
10225        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10226    }
10227
10228    /**
10229     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10230     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10231     * returns 0.0 or 1.0 but no value in between.
10232     *
10233     * Subclasses should override this method to provide a smoother fade transition
10234     * when scrolling occurs.
10235     *
10236     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10237     */
10238    protected float getBottomFadingEdgeStrength() {
10239        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10240                computeVerticalScrollRange() ? 1.0f : 0.0f;
10241    }
10242
10243    /**
10244     * Returns the strength, or intensity, of the left faded edge. The strength is
10245     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10246     * returns 0.0 or 1.0 but no value in between.
10247     *
10248     * Subclasses should override this method to provide a smoother fade transition
10249     * when scrolling occurs.
10250     *
10251     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10252     */
10253    protected float getLeftFadingEdgeStrength() {
10254        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10255    }
10256
10257    /**
10258     * Returns the strength, or intensity, of the right faded edge. The strength is
10259     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10260     * returns 0.0 or 1.0 but no value in between.
10261     *
10262     * Subclasses should override this method to provide a smoother fade transition
10263     * when scrolling occurs.
10264     *
10265     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10266     */
10267    protected float getRightFadingEdgeStrength() {
10268        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10269                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10270    }
10271
10272    /**
10273     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10274     * scrollbar is not drawn by default.</p>
10275     *
10276     * @return true if the horizontal scrollbar should be painted, false
10277     *         otherwise
10278     *
10279     * @see #setHorizontalScrollBarEnabled(boolean)
10280     */
10281    public boolean isHorizontalScrollBarEnabled() {
10282        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10283    }
10284
10285    /**
10286     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10287     * scrollbar is not drawn by default.</p>
10288     *
10289     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10290     *                                   be painted
10291     *
10292     * @see #isHorizontalScrollBarEnabled()
10293     */
10294    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10295        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10296            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10297            computeOpaqueFlags();
10298            resolvePadding();
10299        }
10300    }
10301
10302    /**
10303     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10304     * scrollbar is not drawn by default.</p>
10305     *
10306     * @return true if the vertical scrollbar should be painted, false
10307     *         otherwise
10308     *
10309     * @see #setVerticalScrollBarEnabled(boolean)
10310     */
10311    public boolean isVerticalScrollBarEnabled() {
10312        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10313    }
10314
10315    /**
10316     * <p>Define whether the vertical scrollbar should be drawn or not. The
10317     * scrollbar is not drawn by default.</p>
10318     *
10319     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10320     *                                 be painted
10321     *
10322     * @see #isVerticalScrollBarEnabled()
10323     */
10324    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10325        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10326            mViewFlags ^= SCROLLBARS_VERTICAL;
10327            computeOpaqueFlags();
10328            resolvePadding();
10329        }
10330    }
10331
10332    /**
10333     * @hide
10334     */
10335    protected void recomputePadding() {
10336        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10337    }
10338
10339    /**
10340     * Define whether scrollbars will fade when the view is not scrolling.
10341     *
10342     * @param fadeScrollbars wheter to enable fading
10343     *
10344     * @attr ref android.R.styleable#View_fadeScrollbars
10345     */
10346    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10347        initScrollCache();
10348        final ScrollabilityCache scrollabilityCache = mScrollCache;
10349        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10350        if (fadeScrollbars) {
10351            scrollabilityCache.state = ScrollabilityCache.OFF;
10352        } else {
10353            scrollabilityCache.state = ScrollabilityCache.ON;
10354        }
10355    }
10356
10357    /**
10358     *
10359     * Returns true if scrollbars will fade when this view is not scrolling
10360     *
10361     * @return true if scrollbar fading is enabled
10362     *
10363     * @attr ref android.R.styleable#View_fadeScrollbars
10364     */
10365    public boolean isScrollbarFadingEnabled() {
10366        return mScrollCache != null && mScrollCache.fadeScrollBars;
10367    }
10368
10369    /**
10370     *
10371     * Returns the delay before scrollbars fade.
10372     *
10373     * @return the delay before scrollbars fade
10374     *
10375     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10376     */
10377    public int getScrollBarDefaultDelayBeforeFade() {
10378        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10379                mScrollCache.scrollBarDefaultDelayBeforeFade;
10380    }
10381
10382    /**
10383     * Define the delay before scrollbars fade.
10384     *
10385     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10386     *
10387     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10388     */
10389    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10390        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10391    }
10392
10393    /**
10394     *
10395     * Returns the scrollbar fade duration.
10396     *
10397     * @return the scrollbar fade duration
10398     *
10399     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10400     */
10401    public int getScrollBarFadeDuration() {
10402        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10403                mScrollCache.scrollBarFadeDuration;
10404    }
10405
10406    /**
10407     * Define the scrollbar fade duration.
10408     *
10409     * @param scrollBarFadeDuration - the scrollbar fade duration
10410     *
10411     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10412     */
10413    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10414        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10415    }
10416
10417    /**
10418     *
10419     * Returns the scrollbar size.
10420     *
10421     * @return the scrollbar size
10422     *
10423     * @attr ref android.R.styleable#View_scrollbarSize
10424     */
10425    public int getScrollBarSize() {
10426        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10427                mScrollCache.scrollBarSize;
10428    }
10429
10430    /**
10431     * Define the scrollbar size.
10432     *
10433     * @param scrollBarSize - the scrollbar size
10434     *
10435     * @attr ref android.R.styleable#View_scrollbarSize
10436     */
10437    public void setScrollBarSize(int scrollBarSize) {
10438        getScrollCache().scrollBarSize = scrollBarSize;
10439    }
10440
10441    /**
10442     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10443     * inset. When inset, they add to the padding of the view. And the scrollbars
10444     * can be drawn inside the padding area or on the edge of the view. For example,
10445     * if a view has a background drawable and you want to draw the scrollbars
10446     * inside the padding specified by the drawable, you can use
10447     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10448     * appear at the edge of the view, ignoring the padding, then you can use
10449     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10450     * @param style the style of the scrollbars. Should be one of
10451     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10452     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10453     * @see #SCROLLBARS_INSIDE_OVERLAY
10454     * @see #SCROLLBARS_INSIDE_INSET
10455     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10456     * @see #SCROLLBARS_OUTSIDE_INSET
10457     *
10458     * @attr ref android.R.styleable#View_scrollbarStyle
10459     */
10460    public void setScrollBarStyle(int style) {
10461        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10462            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10463            computeOpaqueFlags();
10464            resolvePadding();
10465        }
10466    }
10467
10468    /**
10469     * <p>Returns the current scrollbar style.</p>
10470     * @return the current scrollbar style
10471     * @see #SCROLLBARS_INSIDE_OVERLAY
10472     * @see #SCROLLBARS_INSIDE_INSET
10473     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10474     * @see #SCROLLBARS_OUTSIDE_INSET
10475     *
10476     * @attr ref android.R.styleable#View_scrollbarStyle
10477     */
10478    @ViewDebug.ExportedProperty(mapping = {
10479            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10480            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10481            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10482            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10483    })
10484    public int getScrollBarStyle() {
10485        return mViewFlags & SCROLLBARS_STYLE_MASK;
10486    }
10487
10488    /**
10489     * <p>Compute the horizontal range that the horizontal scrollbar
10490     * represents.</p>
10491     *
10492     * <p>The range is expressed in arbitrary units that must be the same as the
10493     * units used by {@link #computeHorizontalScrollExtent()} and
10494     * {@link #computeHorizontalScrollOffset()}.</p>
10495     *
10496     * <p>The default range is the drawing width of this view.</p>
10497     *
10498     * @return the total horizontal range represented by the horizontal
10499     *         scrollbar
10500     *
10501     * @see #computeHorizontalScrollExtent()
10502     * @see #computeHorizontalScrollOffset()
10503     * @see android.widget.ScrollBarDrawable
10504     */
10505    protected int computeHorizontalScrollRange() {
10506        return getWidth();
10507    }
10508
10509    /**
10510     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10511     * within the horizontal range. This value is used to compute the position
10512     * of the thumb within the scrollbar's track.</p>
10513     *
10514     * <p>The range is expressed in arbitrary units that must be the same as the
10515     * units used by {@link #computeHorizontalScrollRange()} and
10516     * {@link #computeHorizontalScrollExtent()}.</p>
10517     *
10518     * <p>The default offset is the scroll offset of this view.</p>
10519     *
10520     * @return the horizontal offset of the scrollbar's thumb
10521     *
10522     * @see #computeHorizontalScrollRange()
10523     * @see #computeHorizontalScrollExtent()
10524     * @see android.widget.ScrollBarDrawable
10525     */
10526    protected int computeHorizontalScrollOffset() {
10527        return mScrollX;
10528    }
10529
10530    /**
10531     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10532     * within the horizontal range. This value is used to compute the length
10533     * of the thumb within the scrollbar's track.</p>
10534     *
10535     * <p>The range is expressed in arbitrary units that must be the same as the
10536     * units used by {@link #computeHorizontalScrollRange()} and
10537     * {@link #computeHorizontalScrollOffset()}.</p>
10538     *
10539     * <p>The default extent is the drawing width of this view.</p>
10540     *
10541     * @return the horizontal extent of the scrollbar's thumb
10542     *
10543     * @see #computeHorizontalScrollRange()
10544     * @see #computeHorizontalScrollOffset()
10545     * @see android.widget.ScrollBarDrawable
10546     */
10547    protected int computeHorizontalScrollExtent() {
10548        return getWidth();
10549    }
10550
10551    /**
10552     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10553     *
10554     * <p>The range is expressed in arbitrary units that must be the same as the
10555     * units used by {@link #computeVerticalScrollExtent()} and
10556     * {@link #computeVerticalScrollOffset()}.</p>
10557     *
10558     * @return the total vertical range represented by the vertical scrollbar
10559     *
10560     * <p>The default range is the drawing height of this view.</p>
10561     *
10562     * @see #computeVerticalScrollExtent()
10563     * @see #computeVerticalScrollOffset()
10564     * @see android.widget.ScrollBarDrawable
10565     */
10566    protected int computeVerticalScrollRange() {
10567        return getHeight();
10568    }
10569
10570    /**
10571     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10572     * within the horizontal range. This value is used to compute the position
10573     * of the thumb within the scrollbar's track.</p>
10574     *
10575     * <p>The range is expressed in arbitrary units that must be the same as the
10576     * units used by {@link #computeVerticalScrollRange()} and
10577     * {@link #computeVerticalScrollExtent()}.</p>
10578     *
10579     * <p>The default offset is the scroll offset of this view.</p>
10580     *
10581     * @return the vertical offset of the scrollbar's thumb
10582     *
10583     * @see #computeVerticalScrollRange()
10584     * @see #computeVerticalScrollExtent()
10585     * @see android.widget.ScrollBarDrawable
10586     */
10587    protected int computeVerticalScrollOffset() {
10588        return mScrollY;
10589    }
10590
10591    /**
10592     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10593     * within the vertical range. This value is used to compute the length
10594     * of the thumb within the scrollbar's track.</p>
10595     *
10596     * <p>The range is expressed in arbitrary units that must be the same as the
10597     * units used by {@link #computeVerticalScrollRange()} and
10598     * {@link #computeVerticalScrollOffset()}.</p>
10599     *
10600     * <p>The default extent is the drawing height of this view.</p>
10601     *
10602     * @return the vertical extent of the scrollbar's thumb
10603     *
10604     * @see #computeVerticalScrollRange()
10605     * @see #computeVerticalScrollOffset()
10606     * @see android.widget.ScrollBarDrawable
10607     */
10608    protected int computeVerticalScrollExtent() {
10609        return getHeight();
10610    }
10611
10612    /**
10613     * Check if this view can be scrolled horizontally in a certain direction.
10614     *
10615     * @param direction Negative to check scrolling left, positive to check scrolling right.
10616     * @return true if this view can be scrolled in the specified direction, false otherwise.
10617     */
10618    public boolean canScrollHorizontally(int direction) {
10619        final int offset = computeHorizontalScrollOffset();
10620        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10621        if (range == 0) return false;
10622        if (direction < 0) {
10623            return offset > 0;
10624        } else {
10625            return offset < range - 1;
10626        }
10627    }
10628
10629    /**
10630     * Check if this view can be scrolled vertically in a certain direction.
10631     *
10632     * @param direction Negative to check scrolling up, positive to check scrolling down.
10633     * @return true if this view can be scrolled in the specified direction, false otherwise.
10634     */
10635    public boolean canScrollVertically(int direction) {
10636        final int offset = computeVerticalScrollOffset();
10637        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10638        if (range == 0) return false;
10639        if (direction < 0) {
10640            return offset > 0;
10641        } else {
10642            return offset < range - 1;
10643        }
10644    }
10645
10646    /**
10647     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10648     * scrollbars are painted only if they have been awakened first.</p>
10649     *
10650     * @param canvas the canvas on which to draw the scrollbars
10651     *
10652     * @see #awakenScrollBars(int)
10653     */
10654    protected final void onDrawScrollBars(Canvas canvas) {
10655        // scrollbars are drawn only when the animation is running
10656        final ScrollabilityCache cache = mScrollCache;
10657        if (cache != null) {
10658
10659            int state = cache.state;
10660
10661            if (state == ScrollabilityCache.OFF) {
10662                return;
10663            }
10664
10665            boolean invalidate = false;
10666
10667            if (state == ScrollabilityCache.FADING) {
10668                // We're fading -- get our fade interpolation
10669                if (cache.interpolatorValues == null) {
10670                    cache.interpolatorValues = new float[1];
10671                }
10672
10673                float[] values = cache.interpolatorValues;
10674
10675                // Stops the animation if we're done
10676                if (cache.scrollBarInterpolator.timeToValues(values) ==
10677                        Interpolator.Result.FREEZE_END) {
10678                    cache.state = ScrollabilityCache.OFF;
10679                } else {
10680                    cache.scrollBar.setAlpha(Math.round(values[0]));
10681                }
10682
10683                // This will make the scroll bars inval themselves after
10684                // drawing. We only want this when we're fading so that
10685                // we prevent excessive redraws
10686                invalidate = true;
10687            } else {
10688                // We're just on -- but we may have been fading before so
10689                // reset alpha
10690                cache.scrollBar.setAlpha(255);
10691            }
10692
10693
10694            final int viewFlags = mViewFlags;
10695
10696            final boolean drawHorizontalScrollBar =
10697                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10698            final boolean drawVerticalScrollBar =
10699                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
10700                && !isVerticalScrollBarHidden();
10701
10702            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
10703                final int width = mRight - mLeft;
10704                final int height = mBottom - mTop;
10705
10706                final ScrollBarDrawable scrollBar = cache.scrollBar;
10707
10708                final int scrollX = mScrollX;
10709                final int scrollY = mScrollY;
10710                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
10711
10712                int left, top, right, bottom;
10713
10714                if (drawHorizontalScrollBar) {
10715                    int size = scrollBar.getSize(false);
10716                    if (size <= 0) {
10717                        size = cache.scrollBarSize;
10718                    }
10719
10720                    scrollBar.setParameters(computeHorizontalScrollRange(),
10721                                            computeHorizontalScrollOffset(),
10722                                            computeHorizontalScrollExtent(), false);
10723                    final int verticalScrollBarGap = drawVerticalScrollBar ?
10724                            getVerticalScrollbarWidth() : 0;
10725                    top = scrollY + height - size - (mUserPaddingBottom & inside);
10726                    left = scrollX + (mPaddingLeft & inside);
10727                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
10728                    bottom = top + size;
10729                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
10730                    if (invalidate) {
10731                        invalidate(left, top, right, bottom);
10732                    }
10733                }
10734
10735                if (drawVerticalScrollBar) {
10736                    int size = scrollBar.getSize(true);
10737                    if (size <= 0) {
10738                        size = cache.scrollBarSize;
10739                    }
10740
10741                    scrollBar.setParameters(computeVerticalScrollRange(),
10742                                            computeVerticalScrollOffset(),
10743                                            computeVerticalScrollExtent(), true);
10744                    switch (mVerticalScrollbarPosition) {
10745                        default:
10746                        case SCROLLBAR_POSITION_DEFAULT:
10747                        case SCROLLBAR_POSITION_RIGHT:
10748                            left = scrollX + width - size - (mUserPaddingRight & inside);
10749                            break;
10750                        case SCROLLBAR_POSITION_LEFT:
10751                            left = scrollX + (mUserPaddingLeft & inside);
10752                            break;
10753                    }
10754                    top = scrollY + (mPaddingTop & inside);
10755                    right = left + size;
10756                    bottom = scrollY + height - (mUserPaddingBottom & inside);
10757                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
10758                    if (invalidate) {
10759                        invalidate(left, top, right, bottom);
10760                    }
10761                }
10762            }
10763        }
10764    }
10765
10766    /**
10767     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
10768     * FastScroller is visible.
10769     * @return whether to temporarily hide the vertical scrollbar
10770     * @hide
10771     */
10772    protected boolean isVerticalScrollBarHidden() {
10773        return false;
10774    }
10775
10776    /**
10777     * <p>Draw the horizontal scrollbar if
10778     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
10779     *
10780     * @param canvas the canvas on which to draw the scrollbar
10781     * @param scrollBar the scrollbar's drawable
10782     *
10783     * @see #isHorizontalScrollBarEnabled()
10784     * @see #computeHorizontalScrollRange()
10785     * @see #computeHorizontalScrollExtent()
10786     * @see #computeHorizontalScrollOffset()
10787     * @see android.widget.ScrollBarDrawable
10788     * @hide
10789     */
10790    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
10791            int l, int t, int r, int b) {
10792        scrollBar.setBounds(l, t, r, b);
10793        scrollBar.draw(canvas);
10794    }
10795
10796    /**
10797     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
10798     * returns true.</p>
10799     *
10800     * @param canvas the canvas on which to draw the scrollbar
10801     * @param scrollBar the scrollbar's drawable
10802     *
10803     * @see #isVerticalScrollBarEnabled()
10804     * @see #computeVerticalScrollRange()
10805     * @see #computeVerticalScrollExtent()
10806     * @see #computeVerticalScrollOffset()
10807     * @see android.widget.ScrollBarDrawable
10808     * @hide
10809     */
10810    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
10811            int l, int t, int r, int b) {
10812        scrollBar.setBounds(l, t, r, b);
10813        scrollBar.draw(canvas);
10814    }
10815
10816    /**
10817     * Implement this to do your drawing.
10818     *
10819     * @param canvas the canvas on which the background will be drawn
10820     */
10821    protected void onDraw(Canvas canvas) {
10822    }
10823
10824    /*
10825     * Caller is responsible for calling requestLayout if necessary.
10826     * (This allows addViewInLayout to not request a new layout.)
10827     */
10828    void assignParent(ViewParent parent) {
10829        if (mParent == null) {
10830            mParent = parent;
10831        } else if (parent == null) {
10832            mParent = null;
10833        } else {
10834            throw new RuntimeException("view " + this + " being added, but"
10835                    + " it already has a parent");
10836        }
10837    }
10838
10839    /**
10840     * This is called when the view is attached to a window.  At this point it
10841     * has a Surface and will start drawing.  Note that this function is
10842     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
10843     * however it may be called any time before the first onDraw -- including
10844     * before or after {@link #onMeasure(int, int)}.
10845     *
10846     * @see #onDetachedFromWindow()
10847     */
10848    protected void onAttachedToWindow() {
10849        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
10850            mParent.requestTransparentRegion(this);
10851        }
10852        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
10853            initialAwakenScrollBars();
10854            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
10855        }
10856        jumpDrawablesToCurrentState();
10857        // Order is important here: LayoutDirection MUST be resolved before Padding
10858        // and TextDirection
10859        resolveLayoutDirection();
10860        resolvePadding();
10861        resolveTextDirection();
10862        resolveTextAlignment();
10863        clearAccessibilityFocus();
10864        if (isFocused()) {
10865            InputMethodManager imm = InputMethodManager.peekInstance();
10866            imm.focusIn(this);
10867        }
10868    }
10869
10870    /**
10871     * @see #onScreenStateChanged(int)
10872     */
10873    void dispatchScreenStateChanged(int screenState) {
10874        onScreenStateChanged(screenState);
10875    }
10876
10877    /**
10878     * This method is called whenever the state of the screen this view is
10879     * attached to changes. A state change will usually occurs when the screen
10880     * turns on or off (whether it happens automatically or the user does it
10881     * manually.)
10882     *
10883     * @param screenState The new state of the screen. Can be either
10884     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
10885     */
10886    public void onScreenStateChanged(int screenState) {
10887    }
10888
10889    /**
10890     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
10891     */
10892    private boolean hasRtlSupport() {
10893        return mContext.getApplicationInfo().hasRtlSupport();
10894    }
10895
10896    /**
10897     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
10898     * that the parent directionality can and will be resolved before its children.
10899     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
10900     */
10901    public void resolveLayoutDirection() {
10902        // Clear any previous layout direction resolution
10903        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
10904
10905        if (hasRtlSupport()) {
10906            // Set resolved depending on layout direction
10907            switch (getLayoutDirection()) {
10908                case LAYOUT_DIRECTION_INHERIT:
10909                    // If this is root view, no need to look at parent's layout dir.
10910                    if (canResolveLayoutDirection()) {
10911                        ViewGroup viewGroup = ((ViewGroup) mParent);
10912
10913                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
10914                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10915                        }
10916                    } else {
10917                        // Nothing to do, LTR by default
10918                    }
10919                    break;
10920                case LAYOUT_DIRECTION_RTL:
10921                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10922                    break;
10923                case LAYOUT_DIRECTION_LOCALE:
10924                    if(isLayoutDirectionRtl(Locale.getDefault())) {
10925                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
10926                    }
10927                    break;
10928                default:
10929                    // Nothing to do, LTR by default
10930            }
10931        }
10932
10933        // Set to resolved
10934        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
10935        onResolvedLayoutDirectionChanged();
10936        // Resolve padding
10937        resolvePadding();
10938    }
10939
10940    /**
10941     * Called when layout direction has been resolved.
10942     *
10943     * The default implementation does nothing.
10944     */
10945    public void onResolvedLayoutDirectionChanged() {
10946    }
10947
10948    /**
10949     * Resolve padding depending on layout direction.
10950     */
10951    public void resolvePadding() {
10952        // If the user specified the absolute padding (either with android:padding or
10953        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
10954        // use the default padding or the padding from the background drawable
10955        // (stored at this point in mPadding*)
10956        int resolvedLayoutDirection = getResolvedLayoutDirection();
10957        switch (resolvedLayoutDirection) {
10958            case LAYOUT_DIRECTION_RTL:
10959                // Start user padding override Right user padding. Otherwise, if Right user
10960                // padding is not defined, use the default Right padding. If Right user padding
10961                // is defined, just use it.
10962                if (mUserPaddingStart >= 0) {
10963                    mUserPaddingRight = mUserPaddingStart;
10964                } else if (mUserPaddingRight < 0) {
10965                    mUserPaddingRight = mPaddingRight;
10966                }
10967                if (mUserPaddingEnd >= 0) {
10968                    mUserPaddingLeft = mUserPaddingEnd;
10969                } else if (mUserPaddingLeft < 0) {
10970                    mUserPaddingLeft = mPaddingLeft;
10971                }
10972                break;
10973            case LAYOUT_DIRECTION_LTR:
10974            default:
10975                // Start user padding override Left user padding. Otherwise, if Left user
10976                // padding is not defined, use the default left padding. If Left user padding
10977                // is defined, just use it.
10978                if (mUserPaddingStart >= 0) {
10979                    mUserPaddingLeft = mUserPaddingStart;
10980                } else if (mUserPaddingLeft < 0) {
10981                    mUserPaddingLeft = mPaddingLeft;
10982                }
10983                if (mUserPaddingEnd >= 0) {
10984                    mUserPaddingRight = mUserPaddingEnd;
10985                } else if (mUserPaddingRight < 0) {
10986                    mUserPaddingRight = mPaddingRight;
10987                }
10988        }
10989
10990        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
10991
10992        if(isPaddingRelative()) {
10993            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
10994        } else {
10995            recomputePadding();
10996        }
10997        onPaddingChanged(resolvedLayoutDirection);
10998    }
10999
11000    /**
11001     * Resolve padding depending on the layout direction. Subclasses that care about
11002     * padding resolution should override this method. The default implementation does
11003     * nothing.
11004     *
11005     * @param layoutDirection the direction of the layout
11006     *
11007     * @see {@link #LAYOUT_DIRECTION_LTR}
11008     * @see {@link #LAYOUT_DIRECTION_RTL}
11009     */
11010    public void onPaddingChanged(int layoutDirection) {
11011    }
11012
11013    /**
11014     * Check if layout direction resolution can be done.
11015     *
11016     * @return true if layout direction resolution can be done otherwise return false.
11017     */
11018    public boolean canResolveLayoutDirection() {
11019        switch (getLayoutDirection()) {
11020            case LAYOUT_DIRECTION_INHERIT:
11021                return (mParent != null) && (mParent instanceof ViewGroup);
11022            default:
11023                return true;
11024        }
11025    }
11026
11027    /**
11028     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11029     * when reset is done.
11030     */
11031    public void resetResolvedLayoutDirection() {
11032        // Reset the current resolved bits
11033        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11034        onResolvedLayoutDirectionReset();
11035        // Reset also the text direction
11036        resetResolvedTextDirection();
11037    }
11038
11039    /**
11040     * Called during reset of resolved layout direction.
11041     *
11042     * Subclasses need to override this method to clear cached information that depends on the
11043     * resolved layout direction, or to inform child views that inherit their layout direction.
11044     *
11045     * The default implementation does nothing.
11046     */
11047    public void onResolvedLayoutDirectionReset() {
11048    }
11049
11050    /**
11051     * Check if a Locale uses an RTL script.
11052     *
11053     * @param locale Locale to check
11054     * @return true if the Locale uses an RTL script.
11055     */
11056    protected static boolean isLayoutDirectionRtl(Locale locale) {
11057        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11058    }
11059
11060    /**
11061     * This is called when the view is detached from a window.  At this point it
11062     * no longer has a surface for drawing.
11063     *
11064     * @see #onAttachedToWindow()
11065     */
11066    protected void onDetachedFromWindow() {
11067        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11068
11069        removeUnsetPressCallback();
11070        removeLongPressCallback();
11071        removePerformClickCallback();
11072        removeSendViewScrolledAccessibilityEventCallback();
11073
11074        destroyDrawingCache();
11075
11076        destroyLayer(false);
11077
11078        if (mAttachInfo != null) {
11079            if (mDisplayList != null) {
11080                mAttachInfo.mViewRootImpl.invalidateDisplayList(mDisplayList);
11081            }
11082            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11083        } else {
11084            if (mDisplayList != null) {
11085                // Should never happen
11086                mDisplayList.invalidate();
11087            }
11088        }
11089
11090        mCurrentAnimation = null;
11091
11092        resetResolvedLayoutDirection();
11093        resetResolvedTextAlignment();
11094        resetAccessibilityStateChanged();
11095        clearAccessibilityFocus();
11096    }
11097
11098    /**
11099     * @return The number of times this view has been attached to a window
11100     */
11101    protected int getWindowAttachCount() {
11102        return mWindowAttachCount;
11103    }
11104
11105    /**
11106     * Retrieve a unique token identifying the window this view is attached to.
11107     * @return Return the window's token for use in
11108     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11109     */
11110    public IBinder getWindowToken() {
11111        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11112    }
11113
11114    /**
11115     * Retrieve a unique token identifying the top-level "real" window of
11116     * the window that this view is attached to.  That is, this is like
11117     * {@link #getWindowToken}, except if the window this view in is a panel
11118     * window (attached to another containing window), then the token of
11119     * the containing window is returned instead.
11120     *
11121     * @return Returns the associated window token, either
11122     * {@link #getWindowToken()} or the containing window's token.
11123     */
11124    public IBinder getApplicationWindowToken() {
11125        AttachInfo ai = mAttachInfo;
11126        if (ai != null) {
11127            IBinder appWindowToken = ai.mPanelParentWindowToken;
11128            if (appWindowToken == null) {
11129                appWindowToken = ai.mWindowToken;
11130            }
11131            return appWindowToken;
11132        }
11133        return null;
11134    }
11135
11136    /**
11137     * Retrieve private session object this view hierarchy is using to
11138     * communicate with the window manager.
11139     * @return the session object to communicate with the window manager
11140     */
11141    /*package*/ IWindowSession getWindowSession() {
11142        return mAttachInfo != null ? mAttachInfo.mSession : null;
11143    }
11144
11145    /**
11146     * @param info the {@link android.view.View.AttachInfo} to associated with
11147     *        this view
11148     */
11149    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11150        //System.out.println("Attached! " + this);
11151        mAttachInfo = info;
11152        mWindowAttachCount++;
11153        // We will need to evaluate the drawable state at least once.
11154        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11155        if (mFloatingTreeObserver != null) {
11156            info.mTreeObserver.merge(mFloatingTreeObserver);
11157            mFloatingTreeObserver = null;
11158        }
11159        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11160            mAttachInfo.mScrollContainers.add(this);
11161            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11162        }
11163        performCollectViewAttributes(mAttachInfo, visibility);
11164        onAttachedToWindow();
11165
11166        ListenerInfo li = mListenerInfo;
11167        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11168                li != null ? li.mOnAttachStateChangeListeners : null;
11169        if (listeners != null && listeners.size() > 0) {
11170            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11171            // perform the dispatching. The iterator is a safe guard against listeners that
11172            // could mutate the list by calling the various add/remove methods. This prevents
11173            // the array from being modified while we iterate it.
11174            for (OnAttachStateChangeListener listener : listeners) {
11175                listener.onViewAttachedToWindow(this);
11176            }
11177        }
11178
11179        int vis = info.mWindowVisibility;
11180        if (vis != GONE) {
11181            onWindowVisibilityChanged(vis);
11182        }
11183        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11184            // If nobody has evaluated the drawable state yet, then do it now.
11185            refreshDrawableState();
11186        }
11187    }
11188
11189    void dispatchDetachedFromWindow() {
11190        AttachInfo info = mAttachInfo;
11191        if (info != null) {
11192            int vis = info.mWindowVisibility;
11193            if (vis != GONE) {
11194                onWindowVisibilityChanged(GONE);
11195            }
11196        }
11197
11198        onDetachedFromWindow();
11199
11200        ListenerInfo li = mListenerInfo;
11201        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11202                li != null ? li.mOnAttachStateChangeListeners : null;
11203        if (listeners != null && listeners.size() > 0) {
11204            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11205            // perform the dispatching. The iterator is a safe guard against listeners that
11206            // could mutate the list by calling the various add/remove methods. This prevents
11207            // the array from being modified while we iterate it.
11208            for (OnAttachStateChangeListener listener : listeners) {
11209                listener.onViewDetachedFromWindow(this);
11210            }
11211        }
11212
11213        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11214            mAttachInfo.mScrollContainers.remove(this);
11215            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11216        }
11217
11218        mAttachInfo = null;
11219    }
11220
11221    /**
11222     * Store this view hierarchy's frozen state into the given container.
11223     *
11224     * @param container The SparseArray in which to save the view's state.
11225     *
11226     * @see #restoreHierarchyState(android.util.SparseArray)
11227     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11228     * @see #onSaveInstanceState()
11229     */
11230    public void saveHierarchyState(SparseArray<Parcelable> container) {
11231        dispatchSaveInstanceState(container);
11232    }
11233
11234    /**
11235     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11236     * this view and its children. May be overridden to modify how freezing happens to a
11237     * view's children; for example, some views may want to not store state for their children.
11238     *
11239     * @param container The SparseArray in which to save the view's state.
11240     *
11241     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11242     * @see #saveHierarchyState(android.util.SparseArray)
11243     * @see #onSaveInstanceState()
11244     */
11245    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11246        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11247            mPrivateFlags &= ~SAVE_STATE_CALLED;
11248            Parcelable state = onSaveInstanceState();
11249            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11250                throw new IllegalStateException(
11251                        "Derived class did not call super.onSaveInstanceState()");
11252            }
11253            if (state != null) {
11254                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11255                // + ": " + state);
11256                container.put(mID, state);
11257            }
11258        }
11259    }
11260
11261    /**
11262     * Hook allowing a view to generate a representation of its internal state
11263     * that can later be used to create a new instance with that same state.
11264     * This state should only contain information that is not persistent or can
11265     * not be reconstructed later. For example, you will never store your
11266     * current position on screen because that will be computed again when a
11267     * new instance of the view is placed in its view hierarchy.
11268     * <p>
11269     * Some examples of things you may store here: the current cursor position
11270     * in a text view (but usually not the text itself since that is stored in a
11271     * content provider or other persistent storage), the currently selected
11272     * item in a list view.
11273     *
11274     * @return Returns a Parcelable object containing the view's current dynamic
11275     *         state, or null if there is nothing interesting to save. The
11276     *         default implementation returns null.
11277     * @see #onRestoreInstanceState(android.os.Parcelable)
11278     * @see #saveHierarchyState(android.util.SparseArray)
11279     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11280     * @see #setSaveEnabled(boolean)
11281     */
11282    protected Parcelable onSaveInstanceState() {
11283        mPrivateFlags |= SAVE_STATE_CALLED;
11284        return BaseSavedState.EMPTY_STATE;
11285    }
11286
11287    /**
11288     * Restore this view hierarchy's frozen state from the given container.
11289     *
11290     * @param container The SparseArray which holds previously frozen states.
11291     *
11292     * @see #saveHierarchyState(android.util.SparseArray)
11293     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11294     * @see #onRestoreInstanceState(android.os.Parcelable)
11295     */
11296    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11297        dispatchRestoreInstanceState(container);
11298    }
11299
11300    /**
11301     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11302     * state for this view and its children. May be overridden to modify how restoring
11303     * happens to a view's children; for example, some views may want to not store state
11304     * for their children.
11305     *
11306     * @param container The SparseArray which holds previously saved state.
11307     *
11308     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11309     * @see #restoreHierarchyState(android.util.SparseArray)
11310     * @see #onRestoreInstanceState(android.os.Parcelable)
11311     */
11312    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11313        if (mID != NO_ID) {
11314            Parcelable state = container.get(mID);
11315            if (state != null) {
11316                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11317                // + ": " + state);
11318                mPrivateFlags &= ~SAVE_STATE_CALLED;
11319                onRestoreInstanceState(state);
11320                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11321                    throw new IllegalStateException(
11322                            "Derived class did not call super.onRestoreInstanceState()");
11323                }
11324            }
11325        }
11326    }
11327
11328    /**
11329     * Hook allowing a view to re-apply a representation of its internal state that had previously
11330     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11331     * null state.
11332     *
11333     * @param state The frozen state that had previously been returned by
11334     *        {@link #onSaveInstanceState}.
11335     *
11336     * @see #onSaveInstanceState()
11337     * @see #restoreHierarchyState(android.util.SparseArray)
11338     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11339     */
11340    protected void onRestoreInstanceState(Parcelable state) {
11341        mPrivateFlags |= SAVE_STATE_CALLED;
11342        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11343            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11344                    + "received " + state.getClass().toString() + " instead. This usually happens "
11345                    + "when two views of different type have the same id in the same hierarchy. "
11346                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11347                    + "other views do not use the same id.");
11348        }
11349    }
11350
11351    /**
11352     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11353     *
11354     * @return the drawing start time in milliseconds
11355     */
11356    public long getDrawingTime() {
11357        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11358    }
11359
11360    /**
11361     * <p>Enables or disables the duplication of the parent's state into this view. When
11362     * duplication is enabled, this view gets its drawable state from its parent rather
11363     * than from its own internal properties.</p>
11364     *
11365     * <p>Note: in the current implementation, setting this property to true after the
11366     * view was added to a ViewGroup might have no effect at all. This property should
11367     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11368     *
11369     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11370     * property is enabled, an exception will be thrown.</p>
11371     *
11372     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11373     * parent, these states should not be affected by this method.</p>
11374     *
11375     * @param enabled True to enable duplication of the parent's drawable state, false
11376     *                to disable it.
11377     *
11378     * @see #getDrawableState()
11379     * @see #isDuplicateParentStateEnabled()
11380     */
11381    public void setDuplicateParentStateEnabled(boolean enabled) {
11382        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11383    }
11384
11385    /**
11386     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11387     *
11388     * @return True if this view's drawable state is duplicated from the parent,
11389     *         false otherwise
11390     *
11391     * @see #getDrawableState()
11392     * @see #setDuplicateParentStateEnabled(boolean)
11393     */
11394    public boolean isDuplicateParentStateEnabled() {
11395        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11396    }
11397
11398    /**
11399     * <p>Specifies the type of layer backing this view. The layer can be
11400     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11401     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11402     *
11403     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11404     * instance that controls how the layer is composed on screen. The following
11405     * properties of the paint are taken into account when composing the layer:</p>
11406     * <ul>
11407     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11408     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11409     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11410     * </ul>
11411     *
11412     * <p>If this view has an alpha value set to < 1.0 by calling
11413     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11414     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11415     * equivalent to setting a hardware layer on this view and providing a paint with
11416     * the desired alpha value.<p>
11417     *
11418     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11419     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11420     * for more information on when and how to use layers.</p>
11421     *
11422     * @param layerType The ype of layer to use with this view, must be one of
11423     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11424     *        {@link #LAYER_TYPE_HARDWARE}
11425     * @param paint The paint used to compose the layer. This argument is optional
11426     *        and can be null. It is ignored when the layer type is
11427     *        {@link #LAYER_TYPE_NONE}
11428     *
11429     * @see #getLayerType()
11430     * @see #LAYER_TYPE_NONE
11431     * @see #LAYER_TYPE_SOFTWARE
11432     * @see #LAYER_TYPE_HARDWARE
11433     * @see #setAlpha(float)
11434     *
11435     * @attr ref android.R.styleable#View_layerType
11436     */
11437    public void setLayerType(int layerType, Paint paint) {
11438        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11439            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11440                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11441        }
11442
11443        if (layerType == mLayerType) {
11444            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11445                mLayerPaint = paint == null ? new Paint() : paint;
11446                invalidateParentCaches();
11447                invalidate(true);
11448            }
11449            return;
11450        }
11451
11452        // Destroy any previous software drawing cache if needed
11453        switch (mLayerType) {
11454            case LAYER_TYPE_HARDWARE:
11455                destroyLayer(false);
11456                // fall through - non-accelerated views may use software layer mechanism instead
11457            case LAYER_TYPE_SOFTWARE:
11458                destroyDrawingCache();
11459                break;
11460            default:
11461                break;
11462        }
11463
11464        mLayerType = layerType;
11465        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11466        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11467        mLocalDirtyRect = layerDisabled ? null : new Rect();
11468
11469        invalidateParentCaches();
11470        invalidate(true);
11471    }
11472
11473    /**
11474     * Indicates whether this view has a static layer. A view with layer type
11475     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11476     * dynamic.
11477     */
11478    boolean hasStaticLayer() {
11479        return true;
11480    }
11481
11482    /**
11483     * Indicates what type of layer is currently associated with this view. By default
11484     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11485     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11486     * for more information on the different types of layers.
11487     *
11488     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11489     *         {@link #LAYER_TYPE_HARDWARE}
11490     *
11491     * @see #setLayerType(int, android.graphics.Paint)
11492     * @see #buildLayer()
11493     * @see #LAYER_TYPE_NONE
11494     * @see #LAYER_TYPE_SOFTWARE
11495     * @see #LAYER_TYPE_HARDWARE
11496     */
11497    public int getLayerType() {
11498        return mLayerType;
11499    }
11500
11501    /**
11502     * Forces this view's layer to be created and this view to be rendered
11503     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11504     * invoking this method will have no effect.
11505     *
11506     * This method can for instance be used to render a view into its layer before
11507     * starting an animation. If this view is complex, rendering into the layer
11508     * before starting the animation will avoid skipping frames.
11509     *
11510     * @throws IllegalStateException If this view is not attached to a window
11511     *
11512     * @see #setLayerType(int, android.graphics.Paint)
11513     */
11514    public void buildLayer() {
11515        if (mLayerType == LAYER_TYPE_NONE) return;
11516
11517        if (mAttachInfo == null) {
11518            throw new IllegalStateException("This view must be attached to a window first");
11519        }
11520
11521        switch (mLayerType) {
11522            case LAYER_TYPE_HARDWARE:
11523                if (mAttachInfo.mHardwareRenderer != null &&
11524                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11525                        mAttachInfo.mHardwareRenderer.validate()) {
11526                    getHardwareLayer();
11527                }
11528                break;
11529            case LAYER_TYPE_SOFTWARE:
11530                buildDrawingCache(true);
11531                break;
11532        }
11533    }
11534
11535    // Make sure the HardwareRenderer.validate() was invoked before calling this method
11536    void flushLayer() {
11537        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
11538            mHardwareLayer.flush();
11539        }
11540    }
11541
11542    /**
11543     * <p>Returns a hardware layer that can be used to draw this view again
11544     * without executing its draw method.</p>
11545     *
11546     * @return A HardwareLayer ready to render, or null if an error occurred.
11547     */
11548    HardwareLayer getHardwareLayer() {
11549        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11550                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11551            return null;
11552        }
11553
11554        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11555
11556        final int width = mRight - mLeft;
11557        final int height = mBottom - mTop;
11558
11559        if (width == 0 || height == 0) {
11560            return null;
11561        }
11562
11563        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11564            if (mHardwareLayer == null) {
11565                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11566                        width, height, isOpaque());
11567                mLocalDirtyRect.set(0, 0, width, height);
11568            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11569                mHardwareLayer.resize(width, height);
11570                mLocalDirtyRect.set(0, 0, width, height);
11571            }
11572
11573            // The layer is not valid if the underlying GPU resources cannot be allocated
11574            if (!mHardwareLayer.isValid()) {
11575                return null;
11576            }
11577
11578            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11579            mLocalDirtyRect.setEmpty();
11580        }
11581
11582        return mHardwareLayer;
11583    }
11584
11585    /**
11586     * Destroys this View's hardware layer if possible.
11587     *
11588     * @return True if the layer was destroyed, false otherwise.
11589     *
11590     * @see #setLayerType(int, android.graphics.Paint)
11591     * @see #LAYER_TYPE_HARDWARE
11592     */
11593    boolean destroyLayer(boolean valid) {
11594        if (mHardwareLayer != null) {
11595            AttachInfo info = mAttachInfo;
11596            if (info != null && info.mHardwareRenderer != null &&
11597                    info.mHardwareRenderer.isEnabled() &&
11598                    (valid || info.mHardwareRenderer.validate())) {
11599                mHardwareLayer.destroy();
11600                mHardwareLayer = null;
11601
11602                invalidate(true);
11603                invalidateParentCaches();
11604            }
11605            return true;
11606        }
11607        return false;
11608    }
11609
11610    /**
11611     * Destroys all hardware rendering resources. This method is invoked
11612     * when the system needs to reclaim resources. Upon execution of this
11613     * method, you should free any OpenGL resources created by the view.
11614     *
11615     * Note: you <strong>must</strong> call
11616     * <code>super.destroyHardwareResources()</code> when overriding
11617     * this method.
11618     *
11619     * @hide
11620     */
11621    protected void destroyHardwareResources() {
11622        destroyLayer(true);
11623    }
11624
11625    /**
11626     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11627     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11628     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11629     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11630     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11631     * null.</p>
11632     *
11633     * <p>Enabling the drawing cache is similar to
11634     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11635     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11636     * drawing cache has no effect on rendering because the system uses a different mechanism
11637     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11638     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11639     * for information on how to enable software and hardware layers.</p>
11640     *
11641     * <p>This API can be used to manually generate
11642     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11643     * {@link #getDrawingCache()}.</p>
11644     *
11645     * @param enabled true to enable the drawing cache, false otherwise
11646     *
11647     * @see #isDrawingCacheEnabled()
11648     * @see #getDrawingCache()
11649     * @see #buildDrawingCache()
11650     * @see #setLayerType(int, android.graphics.Paint)
11651     */
11652    public void setDrawingCacheEnabled(boolean enabled) {
11653        mCachingFailed = false;
11654        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
11655    }
11656
11657    /**
11658     * <p>Indicates whether the drawing cache is enabled for this view.</p>
11659     *
11660     * @return true if the drawing cache is enabled
11661     *
11662     * @see #setDrawingCacheEnabled(boolean)
11663     * @see #getDrawingCache()
11664     */
11665    @ViewDebug.ExportedProperty(category = "drawing")
11666    public boolean isDrawingCacheEnabled() {
11667        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
11668    }
11669
11670    /**
11671     * Debugging utility which recursively outputs the dirty state of a view and its
11672     * descendants.
11673     *
11674     * @hide
11675     */
11676    @SuppressWarnings({"UnusedDeclaration"})
11677    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
11678        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
11679                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
11680                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
11681                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
11682        if (clear) {
11683            mPrivateFlags &= clearMask;
11684        }
11685        if (this instanceof ViewGroup) {
11686            ViewGroup parent = (ViewGroup) this;
11687            final int count = parent.getChildCount();
11688            for (int i = 0; i < count; i++) {
11689                final View child = parent.getChildAt(i);
11690                child.outputDirtyFlags(indent + "  ", clear, clearMask);
11691            }
11692        }
11693    }
11694
11695    /**
11696     * This method is used by ViewGroup to cause its children to restore or recreate their
11697     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
11698     * to recreate its own display list, which would happen if it went through the normal
11699     * draw/dispatchDraw mechanisms.
11700     *
11701     * @hide
11702     */
11703    protected void dispatchGetDisplayList() {}
11704
11705    /**
11706     * A view that is not attached or hardware accelerated cannot create a display list.
11707     * This method checks these conditions and returns the appropriate result.
11708     *
11709     * @return true if view has the ability to create a display list, false otherwise.
11710     *
11711     * @hide
11712     */
11713    public boolean canHaveDisplayList() {
11714        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
11715    }
11716
11717    /**
11718     * @return The HardwareRenderer associated with that view or null if hardware rendering
11719     * is not supported or this this has not been attached to a window.
11720     *
11721     * @hide
11722     */
11723    public HardwareRenderer getHardwareRenderer() {
11724        if (mAttachInfo != null) {
11725            return mAttachInfo.mHardwareRenderer;
11726        }
11727        return null;
11728    }
11729
11730    /**
11731     * Returns a DisplayList. If the incoming displayList is null, one will be created.
11732     * Otherwise, the same display list will be returned (after having been rendered into
11733     * along the way, depending on the invalidation state of the view).
11734     *
11735     * @param displayList The previous version of this displayList, could be null.
11736     * @param isLayer Whether the requester of the display list is a layer. If so,
11737     * the view will avoid creating a layer inside the resulting display list.
11738     * @return A new or reused DisplayList object.
11739     */
11740    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
11741        if (!canHaveDisplayList()) {
11742            return null;
11743        }
11744
11745        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
11746                displayList == null || !displayList.isValid() ||
11747                (!isLayer && mRecreateDisplayList))) {
11748            // Don't need to recreate the display list, just need to tell our
11749            // children to restore/recreate theirs
11750            if (displayList != null && displayList.isValid() &&
11751                    !isLayer && !mRecreateDisplayList) {
11752                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11753                mPrivateFlags &= ~DIRTY_MASK;
11754                dispatchGetDisplayList();
11755
11756                return displayList;
11757            }
11758
11759            if (!isLayer) {
11760                // If we got here, we're recreating it. Mark it as such to ensure that
11761                // we copy in child display lists into ours in drawChild()
11762                mRecreateDisplayList = true;
11763            }
11764            if (displayList == null) {
11765                final String name = getClass().getSimpleName();
11766                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
11767                // If we're creating a new display list, make sure our parent gets invalidated
11768                // since they will need to recreate their display list to account for this
11769                // new child display list.
11770                invalidateParentCaches();
11771            }
11772
11773            boolean caching = false;
11774            final HardwareCanvas canvas = displayList.start();
11775            int restoreCount = 0;
11776            int width = mRight - mLeft;
11777            int height = mBottom - mTop;
11778
11779            try {
11780                canvas.setViewport(width, height);
11781                // The dirty rect should always be null for a display list
11782                canvas.onPreDraw(null);
11783                int layerType = (
11784                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
11785                        getLayerType() : LAYER_TYPE_NONE;
11786                if (!isLayer && layerType != LAYER_TYPE_NONE) {
11787                    if (layerType == LAYER_TYPE_HARDWARE) {
11788                        final HardwareLayer layer = getHardwareLayer();
11789                        if (layer != null && layer.isValid()) {
11790                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
11791                        } else {
11792                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
11793                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
11794                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11795                        }
11796                        caching = true;
11797                    } else {
11798                        buildDrawingCache(true);
11799                        Bitmap cache = getDrawingCache(true);
11800                        if (cache != null) {
11801                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
11802                            caching = true;
11803                        }
11804                    }
11805                } else {
11806
11807                    computeScroll();
11808
11809                    canvas.translate(-mScrollX, -mScrollY);
11810                    if (!isLayer) {
11811                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11812                        mPrivateFlags &= ~DIRTY_MASK;
11813                    }
11814
11815                    // Fast path for layouts with no backgrounds
11816                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11817                        dispatchDraw(canvas);
11818                    } else {
11819                        draw(canvas);
11820                    }
11821                }
11822            } finally {
11823                canvas.onPostDraw();
11824
11825                displayList.end();
11826                displayList.setCaching(caching);
11827                if (isLayer) {
11828                    displayList.setLeftTopRightBottom(0, 0, width, height);
11829                } else {
11830                    setDisplayListProperties(displayList);
11831                }
11832            }
11833        } else if (!isLayer) {
11834            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
11835            mPrivateFlags &= ~DIRTY_MASK;
11836        }
11837
11838        return displayList;
11839    }
11840
11841    /**
11842     * Get the DisplayList for the HardwareLayer
11843     *
11844     * @param layer The HardwareLayer whose DisplayList we want
11845     * @return A DisplayList fopr the specified HardwareLayer
11846     */
11847    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
11848        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
11849        layer.setDisplayList(displayList);
11850        return displayList;
11851    }
11852
11853
11854    /**
11855     * <p>Returns a display list that can be used to draw this view again
11856     * without executing its draw method.</p>
11857     *
11858     * @return A DisplayList ready to replay, or null if caching is not enabled.
11859     *
11860     * @hide
11861     */
11862    public DisplayList getDisplayList() {
11863        mDisplayList = getDisplayList(mDisplayList, false);
11864        return mDisplayList;
11865    }
11866
11867    /**
11868     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
11869     *
11870     * @return A non-scaled bitmap representing this view or null if cache is disabled.
11871     *
11872     * @see #getDrawingCache(boolean)
11873     */
11874    public Bitmap getDrawingCache() {
11875        return getDrawingCache(false);
11876    }
11877
11878    /**
11879     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
11880     * is null when caching is disabled. If caching is enabled and the cache is not ready,
11881     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
11882     * draw from the cache when the cache is enabled. To benefit from the cache, you must
11883     * request the drawing cache by calling this method and draw it on screen if the
11884     * returned bitmap is not null.</p>
11885     *
11886     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11887     * this method will create a bitmap of the same size as this view. Because this bitmap
11888     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11889     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11890     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11891     * size than the view. This implies that your application must be able to handle this
11892     * size.</p>
11893     *
11894     * @param autoScale Indicates whether the generated bitmap should be scaled based on
11895     *        the current density of the screen when the application is in compatibility
11896     *        mode.
11897     *
11898     * @return A bitmap representing this view or null if cache is disabled.
11899     *
11900     * @see #setDrawingCacheEnabled(boolean)
11901     * @see #isDrawingCacheEnabled()
11902     * @see #buildDrawingCache(boolean)
11903     * @see #destroyDrawingCache()
11904     */
11905    public Bitmap getDrawingCache(boolean autoScale) {
11906        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
11907            return null;
11908        }
11909        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
11910            buildDrawingCache(autoScale);
11911        }
11912        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
11913    }
11914
11915    /**
11916     * <p>Frees the resources used by the drawing cache. If you call
11917     * {@link #buildDrawingCache()} manually without calling
11918     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11919     * should cleanup the cache with this method afterwards.</p>
11920     *
11921     * @see #setDrawingCacheEnabled(boolean)
11922     * @see #buildDrawingCache()
11923     * @see #getDrawingCache()
11924     */
11925    public void destroyDrawingCache() {
11926        if (mDrawingCache != null) {
11927            mDrawingCache.recycle();
11928            mDrawingCache = null;
11929        }
11930        if (mUnscaledDrawingCache != null) {
11931            mUnscaledDrawingCache.recycle();
11932            mUnscaledDrawingCache = null;
11933        }
11934    }
11935
11936    /**
11937     * Setting a solid background color for the drawing cache's bitmaps will improve
11938     * performance and memory usage. Note, though that this should only be used if this
11939     * view will always be drawn on top of a solid color.
11940     *
11941     * @param color The background color to use for the drawing cache's bitmap
11942     *
11943     * @see #setDrawingCacheEnabled(boolean)
11944     * @see #buildDrawingCache()
11945     * @see #getDrawingCache()
11946     */
11947    public void setDrawingCacheBackgroundColor(int color) {
11948        if (color != mDrawingCacheBackgroundColor) {
11949            mDrawingCacheBackgroundColor = color;
11950            mPrivateFlags &= ~DRAWING_CACHE_VALID;
11951        }
11952    }
11953
11954    /**
11955     * @see #setDrawingCacheBackgroundColor(int)
11956     *
11957     * @return The background color to used for the drawing cache's bitmap
11958     */
11959    public int getDrawingCacheBackgroundColor() {
11960        return mDrawingCacheBackgroundColor;
11961    }
11962
11963    /**
11964     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
11965     *
11966     * @see #buildDrawingCache(boolean)
11967     */
11968    public void buildDrawingCache() {
11969        buildDrawingCache(false);
11970    }
11971
11972    /**
11973     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
11974     *
11975     * <p>If you call {@link #buildDrawingCache()} manually without calling
11976     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
11977     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
11978     *
11979     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
11980     * this method will create a bitmap of the same size as this view. Because this bitmap
11981     * will be drawn scaled by the parent ViewGroup, the result on screen might show
11982     * scaling artifacts. To avoid such artifacts, you should call this method by setting
11983     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
11984     * size than the view. This implies that your application must be able to handle this
11985     * size.</p>
11986     *
11987     * <p>You should avoid calling this method when hardware acceleration is enabled. If
11988     * you do not need the drawing cache bitmap, calling this method will increase memory
11989     * usage and cause the view to be rendered in software once, thus negatively impacting
11990     * performance.</p>
11991     *
11992     * @see #getDrawingCache()
11993     * @see #destroyDrawingCache()
11994     */
11995    public void buildDrawingCache(boolean autoScale) {
11996        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
11997                mDrawingCache == null : mUnscaledDrawingCache == null)) {
11998            mCachingFailed = false;
11999
12000            if (ViewDebug.TRACE_HIERARCHY) {
12001                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
12002            }
12003
12004            int width = mRight - mLeft;
12005            int height = mBottom - mTop;
12006
12007            final AttachInfo attachInfo = mAttachInfo;
12008            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12009
12010            if (autoScale && scalingRequired) {
12011                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12012                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12013            }
12014
12015            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12016            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12017            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12018
12019            if (width <= 0 || height <= 0 ||
12020                     // Projected bitmap size in bytes
12021                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12022                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12023                destroyDrawingCache();
12024                mCachingFailed = true;
12025                return;
12026            }
12027
12028            boolean clear = true;
12029            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12030
12031            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12032                Bitmap.Config quality;
12033                if (!opaque) {
12034                    // Never pick ARGB_4444 because it looks awful
12035                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12036                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12037                        case DRAWING_CACHE_QUALITY_AUTO:
12038                            quality = Bitmap.Config.ARGB_8888;
12039                            break;
12040                        case DRAWING_CACHE_QUALITY_LOW:
12041                            quality = Bitmap.Config.ARGB_8888;
12042                            break;
12043                        case DRAWING_CACHE_QUALITY_HIGH:
12044                            quality = Bitmap.Config.ARGB_8888;
12045                            break;
12046                        default:
12047                            quality = Bitmap.Config.ARGB_8888;
12048                            break;
12049                    }
12050                } else {
12051                    // Optimization for translucent windows
12052                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12053                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12054                }
12055
12056                // Try to cleanup memory
12057                if (bitmap != null) bitmap.recycle();
12058
12059                try {
12060                    bitmap = Bitmap.createBitmap(width, height, quality);
12061                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12062                    if (autoScale) {
12063                        mDrawingCache = bitmap;
12064                    } else {
12065                        mUnscaledDrawingCache = bitmap;
12066                    }
12067                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12068                } catch (OutOfMemoryError e) {
12069                    // If there is not enough memory to create the bitmap cache, just
12070                    // ignore the issue as bitmap caches are not required to draw the
12071                    // view hierarchy
12072                    if (autoScale) {
12073                        mDrawingCache = null;
12074                    } else {
12075                        mUnscaledDrawingCache = null;
12076                    }
12077                    mCachingFailed = true;
12078                    return;
12079                }
12080
12081                clear = drawingCacheBackgroundColor != 0;
12082            }
12083
12084            Canvas canvas;
12085            if (attachInfo != null) {
12086                canvas = attachInfo.mCanvas;
12087                if (canvas == null) {
12088                    canvas = new Canvas();
12089                }
12090                canvas.setBitmap(bitmap);
12091                // Temporarily clobber the cached Canvas in case one of our children
12092                // is also using a drawing cache. Without this, the children would
12093                // steal the canvas by attaching their own bitmap to it and bad, bad
12094                // thing would happen (invisible views, corrupted drawings, etc.)
12095                attachInfo.mCanvas = null;
12096            } else {
12097                // This case should hopefully never or seldom happen
12098                canvas = new Canvas(bitmap);
12099            }
12100
12101            if (clear) {
12102                bitmap.eraseColor(drawingCacheBackgroundColor);
12103            }
12104
12105            computeScroll();
12106            final int restoreCount = canvas.save();
12107
12108            if (autoScale && scalingRequired) {
12109                final float scale = attachInfo.mApplicationScale;
12110                canvas.scale(scale, scale);
12111            }
12112
12113            canvas.translate(-mScrollX, -mScrollY);
12114
12115            mPrivateFlags |= DRAWN;
12116            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12117                    mLayerType != LAYER_TYPE_NONE) {
12118                mPrivateFlags |= DRAWING_CACHE_VALID;
12119            }
12120
12121            // Fast path for layouts with no backgrounds
12122            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12123                if (ViewDebug.TRACE_HIERARCHY) {
12124                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12125                }
12126                mPrivateFlags &= ~DIRTY_MASK;
12127                dispatchDraw(canvas);
12128            } else {
12129                draw(canvas);
12130            }
12131
12132            canvas.restoreToCount(restoreCount);
12133            canvas.setBitmap(null);
12134
12135            if (attachInfo != null) {
12136                // Restore the cached Canvas for our siblings
12137                attachInfo.mCanvas = canvas;
12138            }
12139        }
12140    }
12141
12142    /**
12143     * Create a snapshot of the view into a bitmap.  We should probably make
12144     * some form of this public, but should think about the API.
12145     */
12146    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12147        int width = mRight - mLeft;
12148        int height = mBottom - mTop;
12149
12150        final AttachInfo attachInfo = mAttachInfo;
12151        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12152        width = (int) ((width * scale) + 0.5f);
12153        height = (int) ((height * scale) + 0.5f);
12154
12155        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12156        if (bitmap == null) {
12157            throw new OutOfMemoryError();
12158        }
12159
12160        Resources resources = getResources();
12161        if (resources != null) {
12162            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12163        }
12164
12165        Canvas canvas;
12166        if (attachInfo != null) {
12167            canvas = attachInfo.mCanvas;
12168            if (canvas == null) {
12169                canvas = new Canvas();
12170            }
12171            canvas.setBitmap(bitmap);
12172            // Temporarily clobber the cached Canvas in case one of our children
12173            // is also using a drawing cache. Without this, the children would
12174            // steal the canvas by attaching their own bitmap to it and bad, bad
12175            // things would happen (invisible views, corrupted drawings, etc.)
12176            attachInfo.mCanvas = null;
12177        } else {
12178            // This case should hopefully never or seldom happen
12179            canvas = new Canvas(bitmap);
12180        }
12181
12182        if ((backgroundColor & 0xff000000) != 0) {
12183            bitmap.eraseColor(backgroundColor);
12184        }
12185
12186        computeScroll();
12187        final int restoreCount = canvas.save();
12188        canvas.scale(scale, scale);
12189        canvas.translate(-mScrollX, -mScrollY);
12190
12191        // Temporarily remove the dirty mask
12192        int flags = mPrivateFlags;
12193        mPrivateFlags &= ~DIRTY_MASK;
12194
12195        // Fast path for layouts with no backgrounds
12196        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12197            dispatchDraw(canvas);
12198        } else {
12199            draw(canvas);
12200        }
12201
12202        mPrivateFlags = flags;
12203
12204        canvas.restoreToCount(restoreCount);
12205        canvas.setBitmap(null);
12206
12207        if (attachInfo != null) {
12208            // Restore the cached Canvas for our siblings
12209            attachInfo.mCanvas = canvas;
12210        }
12211
12212        return bitmap;
12213    }
12214
12215    /**
12216     * Indicates whether this View is currently in edit mode. A View is usually
12217     * in edit mode when displayed within a developer tool. For instance, if
12218     * this View is being drawn by a visual user interface builder, this method
12219     * should return true.
12220     *
12221     * Subclasses should check the return value of this method to provide
12222     * different behaviors if their normal behavior might interfere with the
12223     * host environment. For instance: the class spawns a thread in its
12224     * constructor, the drawing code relies on device-specific features, etc.
12225     *
12226     * This method is usually checked in the drawing code of custom widgets.
12227     *
12228     * @return True if this View is in edit mode, false otherwise.
12229     */
12230    public boolean isInEditMode() {
12231        return false;
12232    }
12233
12234    /**
12235     * If the View draws content inside its padding and enables fading edges,
12236     * it needs to support padding offsets. Padding offsets are added to the
12237     * fading edges to extend the length of the fade so that it covers pixels
12238     * drawn inside the padding.
12239     *
12240     * Subclasses of this class should override this method if they need
12241     * to draw content inside the padding.
12242     *
12243     * @return True if padding offset must be applied, false otherwise.
12244     *
12245     * @see #getLeftPaddingOffset()
12246     * @see #getRightPaddingOffset()
12247     * @see #getTopPaddingOffset()
12248     * @see #getBottomPaddingOffset()
12249     *
12250     * @since CURRENT
12251     */
12252    protected boolean isPaddingOffsetRequired() {
12253        return false;
12254    }
12255
12256    /**
12257     * Amount by which to extend the left fading region. Called only when
12258     * {@link #isPaddingOffsetRequired()} returns true.
12259     *
12260     * @return The left padding offset in pixels.
12261     *
12262     * @see #isPaddingOffsetRequired()
12263     *
12264     * @since CURRENT
12265     */
12266    protected int getLeftPaddingOffset() {
12267        return 0;
12268    }
12269
12270    /**
12271     * Amount by which to extend the right fading region. Called only when
12272     * {@link #isPaddingOffsetRequired()} returns true.
12273     *
12274     * @return The right padding offset in pixels.
12275     *
12276     * @see #isPaddingOffsetRequired()
12277     *
12278     * @since CURRENT
12279     */
12280    protected int getRightPaddingOffset() {
12281        return 0;
12282    }
12283
12284    /**
12285     * Amount by which to extend the top fading region. Called only when
12286     * {@link #isPaddingOffsetRequired()} returns true.
12287     *
12288     * @return The top padding offset in pixels.
12289     *
12290     * @see #isPaddingOffsetRequired()
12291     *
12292     * @since CURRENT
12293     */
12294    protected int getTopPaddingOffset() {
12295        return 0;
12296    }
12297
12298    /**
12299     * Amount by which to extend the bottom fading region. Called only when
12300     * {@link #isPaddingOffsetRequired()} returns true.
12301     *
12302     * @return The bottom padding offset in pixels.
12303     *
12304     * @see #isPaddingOffsetRequired()
12305     *
12306     * @since CURRENT
12307     */
12308    protected int getBottomPaddingOffset() {
12309        return 0;
12310    }
12311
12312    /**
12313     * @hide
12314     * @param offsetRequired
12315     */
12316    protected int getFadeTop(boolean offsetRequired) {
12317        int top = mPaddingTop;
12318        if (offsetRequired) top += getTopPaddingOffset();
12319        return top;
12320    }
12321
12322    /**
12323     * @hide
12324     * @param offsetRequired
12325     */
12326    protected int getFadeHeight(boolean offsetRequired) {
12327        int padding = mPaddingTop;
12328        if (offsetRequired) padding += getTopPaddingOffset();
12329        return mBottom - mTop - mPaddingBottom - padding;
12330    }
12331
12332    /**
12333     * <p>Indicates whether this view is attached to a hardware accelerated
12334     * window or not.</p>
12335     *
12336     * <p>Even if this method returns true, it does not mean that every call
12337     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12338     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12339     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12340     * window is hardware accelerated,
12341     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12342     * return false, and this method will return true.</p>
12343     *
12344     * @return True if the view is attached to a window and the window is
12345     *         hardware accelerated; false in any other case.
12346     */
12347    public boolean isHardwareAccelerated() {
12348        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12349    }
12350
12351    /**
12352     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12353     * case of an active Animation being run on the view.
12354     */
12355    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12356            Animation a, boolean scalingRequired) {
12357        Transformation invalidationTransform;
12358        final int flags = parent.mGroupFlags;
12359        final boolean initialized = a.isInitialized();
12360        if (!initialized) {
12361            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12362            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12363            onAnimationStart();
12364        }
12365
12366        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12367        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12368            if (parent.mInvalidationTransformation == null) {
12369                parent.mInvalidationTransformation = new Transformation();
12370            }
12371            invalidationTransform = parent.mInvalidationTransformation;
12372            a.getTransformation(drawingTime, invalidationTransform, 1f);
12373        } else {
12374            invalidationTransform = parent.mChildTransformation;
12375        }
12376        if (more) {
12377            if (!a.willChangeBounds()) {
12378                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12379                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12380                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12381                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12382                    // The child need to draw an animation, potentially offscreen, so
12383                    // make sure we do not cancel invalidate requests
12384                    parent.mPrivateFlags |= DRAW_ANIMATION;
12385                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12386                }
12387            } else {
12388                if (parent.mInvalidateRegion == null) {
12389                    parent.mInvalidateRegion = new RectF();
12390                }
12391                final RectF region = parent.mInvalidateRegion;
12392                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12393                        invalidationTransform);
12394
12395                // The child need to draw an animation, potentially offscreen, so
12396                // make sure we do not cancel invalidate requests
12397                parent.mPrivateFlags |= DRAW_ANIMATION;
12398
12399                final int left = mLeft + (int) region.left;
12400                final int top = mTop + (int) region.top;
12401                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12402                        top + (int) (region.height() + .5f));
12403            }
12404        }
12405        return more;
12406    }
12407
12408    void setDisplayListProperties() {
12409        setDisplayListProperties(mDisplayList);
12410    }
12411
12412    /**
12413     * This method is called by getDisplayList() when a display list is created or re-rendered.
12414     * It sets or resets the current value of all properties on that display list (resetting is
12415     * necessary when a display list is being re-created, because we need to make sure that
12416     * previously-set transform values
12417     */
12418    void setDisplayListProperties(DisplayList displayList) {
12419        if (displayList != null) {
12420            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12421            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12422            if (mParent instanceof ViewGroup) {
12423                displayList.setClipChildren(
12424                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12425            }
12426            float alpha = 1;
12427            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12428                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12429                ViewGroup parentVG = (ViewGroup) mParent;
12430                final boolean hasTransform =
12431                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12432                if (hasTransform) {
12433                    Transformation transform = parentVG.mChildTransformation;
12434                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12435                    if (transformType != Transformation.TYPE_IDENTITY) {
12436                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12437                            alpha = transform.getAlpha();
12438                        }
12439                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12440                            displayList.setStaticMatrix(transform.getMatrix());
12441                        }
12442                    }
12443                }
12444            }
12445            if (mTransformationInfo != null) {
12446                alpha *= mTransformationInfo.mAlpha;
12447                if (alpha < 1) {
12448                    final int multipliedAlpha = (int) (255 * alpha);
12449                    if (onSetAlpha(multipliedAlpha)) {
12450                        alpha = 1;
12451                    }
12452                }
12453                displayList.setTransformationInfo(alpha,
12454                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12455                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12456                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12457                        mTransformationInfo.mScaleY);
12458                if (mTransformationInfo.mCamera == null) {
12459                    mTransformationInfo.mCamera = new Camera();
12460                    mTransformationInfo.matrix3D = new Matrix();
12461                }
12462                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12463                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12464                    displayList.setPivotX(getPivotX());
12465                    displayList.setPivotY(getPivotY());
12466                }
12467            } else if (alpha < 1) {
12468                displayList.setAlpha(alpha);
12469            }
12470        }
12471    }
12472
12473    /**
12474     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12475     * This draw() method is an implementation detail and is not intended to be overridden or
12476     * to be called from anywhere else other than ViewGroup.drawChild().
12477     */
12478    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12479        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12480        boolean more = false;
12481        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12482        final int flags = parent.mGroupFlags;
12483
12484        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12485            parent.mChildTransformation.clear();
12486            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12487        }
12488
12489        Transformation transformToApply = null;
12490        boolean concatMatrix = false;
12491
12492        boolean scalingRequired = false;
12493        boolean caching;
12494        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
12495
12496        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12497        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12498                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12499            caching = true;
12500            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12501            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12502        } else {
12503            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12504        }
12505
12506        final Animation a = getAnimation();
12507        if (a != null) {
12508            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12509            concatMatrix = a.willChangeTransformationMatrix();
12510            transformToApply = parent.mChildTransformation;
12511        } else if (!useDisplayListProperties &&
12512                (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12513            final boolean hasTransform =
12514                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
12515            if (hasTransform) {
12516                final int transformType = parent.mChildTransformation.getTransformationType();
12517                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12518                        parent.mChildTransformation : null;
12519                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12520            }
12521        }
12522
12523        concatMatrix |= !childHasIdentityMatrix;
12524
12525        // Sets the flag as early as possible to allow draw() implementations
12526        // to call invalidate() successfully when doing animations
12527        mPrivateFlags |= DRAWN;
12528
12529        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12530                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12531            return more;
12532        }
12533
12534        if (hardwareAccelerated) {
12535            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12536            // retain the flag's value temporarily in the mRecreateDisplayList flag
12537            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12538            mPrivateFlags &= ~INVALIDATED;
12539        }
12540
12541        computeScroll();
12542
12543        final int sx = mScrollX;
12544        final int sy = mScrollY;
12545
12546        DisplayList displayList = null;
12547        Bitmap cache = null;
12548        boolean hasDisplayList = false;
12549        if (caching) {
12550            if (!hardwareAccelerated) {
12551                if (layerType != LAYER_TYPE_NONE) {
12552                    layerType = LAYER_TYPE_SOFTWARE;
12553                    buildDrawingCache(true);
12554                }
12555                cache = getDrawingCache(true);
12556            } else {
12557                switch (layerType) {
12558                    case LAYER_TYPE_SOFTWARE:
12559                        if (useDisplayListProperties) {
12560                            hasDisplayList = canHaveDisplayList();
12561                        } else {
12562                            buildDrawingCache(true);
12563                            cache = getDrawingCache(true);
12564                        }
12565                        break;
12566                    case LAYER_TYPE_HARDWARE:
12567                        if (useDisplayListProperties) {
12568                            hasDisplayList = canHaveDisplayList();
12569                        }
12570                        break;
12571                    case LAYER_TYPE_NONE:
12572                        // Delay getting the display list until animation-driven alpha values are
12573                        // set up and possibly passed on to the view
12574                        hasDisplayList = canHaveDisplayList();
12575                        break;
12576                }
12577            }
12578        }
12579        useDisplayListProperties &= hasDisplayList;
12580        if (useDisplayListProperties) {
12581            displayList = getDisplayList();
12582            if (!displayList.isValid()) {
12583                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12584                // to getDisplayList(), the display list will be marked invalid and we should not
12585                // try to use it again.
12586                displayList = null;
12587                hasDisplayList = false;
12588                useDisplayListProperties = false;
12589            }
12590        }
12591
12592        final boolean hasNoCache = cache == null || hasDisplayList;
12593        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12594                layerType != LAYER_TYPE_HARDWARE;
12595
12596        int restoreTo = -1;
12597        if (!useDisplayListProperties || transformToApply != null) {
12598            restoreTo = canvas.save();
12599        }
12600        if (offsetForScroll) {
12601            canvas.translate(mLeft - sx, mTop - sy);
12602        } else {
12603            if (!useDisplayListProperties) {
12604                canvas.translate(mLeft, mTop);
12605            }
12606            if (scalingRequired) {
12607                if (useDisplayListProperties) {
12608                    // TODO: Might not need this if we put everything inside the DL
12609                    restoreTo = canvas.save();
12610                }
12611                // mAttachInfo cannot be null, otherwise scalingRequired == false
12612                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12613                canvas.scale(scale, scale);
12614            }
12615        }
12616
12617        float alpha = useDisplayListProperties ? 1 : getAlpha();
12618        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
12619            if (transformToApply != null || !childHasIdentityMatrix) {
12620                int transX = 0;
12621                int transY = 0;
12622
12623                if (offsetForScroll) {
12624                    transX = -sx;
12625                    transY = -sy;
12626                }
12627
12628                if (transformToApply != null) {
12629                    if (concatMatrix) {
12630                        if (useDisplayListProperties) {
12631                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12632                        } else {
12633                            // Undo the scroll translation, apply the transformation matrix,
12634                            // then redo the scroll translate to get the correct result.
12635                            canvas.translate(-transX, -transY);
12636                            canvas.concat(transformToApply.getMatrix());
12637                            canvas.translate(transX, transY);
12638                        }
12639                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12640                    }
12641
12642                    float transformAlpha = transformToApply.getAlpha();
12643                    if (transformAlpha < 1) {
12644                        alpha *= transformToApply.getAlpha();
12645                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12646                    }
12647                }
12648
12649                if (!childHasIdentityMatrix && !useDisplayListProperties) {
12650                    canvas.translate(-transX, -transY);
12651                    canvas.concat(getMatrix());
12652                    canvas.translate(transX, transY);
12653                }
12654            }
12655
12656            if (alpha < 1) {
12657                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12658                if (hasNoCache) {
12659                    final int multipliedAlpha = (int) (255 * alpha);
12660                    if (!onSetAlpha(multipliedAlpha)) {
12661                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12662                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
12663                                layerType != LAYER_TYPE_NONE) {
12664                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
12665                        }
12666                        if (useDisplayListProperties) {
12667                            displayList.setAlpha(alpha * getAlpha());
12668                        } else  if (layerType == LAYER_TYPE_NONE) {
12669                            final int scrollX = hasDisplayList ? 0 : sx;
12670                            final int scrollY = hasDisplayList ? 0 : sy;
12671                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
12672                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
12673                        }
12674                    } else {
12675                        // Alpha is handled by the child directly, clobber the layer's alpha
12676                        mPrivateFlags |= ALPHA_SET;
12677                    }
12678                }
12679            }
12680        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12681            onSetAlpha(255);
12682            mPrivateFlags &= ~ALPHA_SET;
12683        }
12684
12685        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
12686                !useDisplayListProperties) {
12687            if (offsetForScroll) {
12688                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
12689            } else {
12690                if (!scalingRequired || cache == null) {
12691                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
12692                } else {
12693                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
12694                }
12695            }
12696        }
12697
12698        if (!useDisplayListProperties && hasDisplayList) {
12699            displayList = getDisplayList();
12700            if (!displayList.isValid()) {
12701                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12702                // to getDisplayList(), the display list will be marked invalid and we should not
12703                // try to use it again.
12704                displayList = null;
12705                hasDisplayList = false;
12706            }
12707        }
12708
12709        if (hasNoCache) {
12710            boolean layerRendered = false;
12711            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
12712                final HardwareLayer layer = getHardwareLayer();
12713                if (layer != null && layer.isValid()) {
12714                    mLayerPaint.setAlpha((int) (alpha * 255));
12715                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
12716                    layerRendered = true;
12717                } else {
12718                    final int scrollX = hasDisplayList ? 0 : sx;
12719                    final int scrollY = hasDisplayList ? 0 : sy;
12720                    canvas.saveLayer(scrollX, scrollY,
12721                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
12722                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12723                }
12724            }
12725
12726            if (!layerRendered) {
12727                if (!hasDisplayList) {
12728                    // Fast path for layouts with no backgrounds
12729                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12730                        if (ViewDebug.TRACE_HIERARCHY) {
12731                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
12732                        }
12733                        mPrivateFlags &= ~DIRTY_MASK;
12734                        dispatchDraw(canvas);
12735                    } else {
12736                        draw(canvas);
12737                    }
12738                } else {
12739                    mPrivateFlags &= ~DIRTY_MASK;
12740                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
12741                }
12742            }
12743        } else if (cache != null) {
12744            mPrivateFlags &= ~DIRTY_MASK;
12745            Paint cachePaint;
12746
12747            if (layerType == LAYER_TYPE_NONE) {
12748                cachePaint = parent.mCachePaint;
12749                if (cachePaint == null) {
12750                    cachePaint = new Paint();
12751                    cachePaint.setDither(false);
12752                    parent.mCachePaint = cachePaint;
12753                }
12754                if (alpha < 1) {
12755                    cachePaint.setAlpha((int) (alpha * 255));
12756                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12757                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
12758                    cachePaint.setAlpha(255);
12759                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
12760                }
12761            } else {
12762                cachePaint = mLayerPaint;
12763                cachePaint.setAlpha((int) (alpha * 255));
12764            }
12765            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
12766        }
12767
12768        if (restoreTo >= 0) {
12769            canvas.restoreToCount(restoreTo);
12770        }
12771
12772        if (a != null && !more) {
12773            if (!hardwareAccelerated && !a.getFillAfter()) {
12774                onSetAlpha(255);
12775            }
12776            parent.finishAnimatingView(this, a);
12777        }
12778
12779        if (more && hardwareAccelerated) {
12780            // invalidation is the trigger to recreate display lists, so if we're using
12781            // display lists to render, force an invalidate to allow the animation to
12782            // continue drawing another frame
12783            parent.invalidate(true);
12784            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
12785                // alpha animations should cause the child to recreate its display list
12786                invalidate(true);
12787            }
12788        }
12789
12790        mRecreateDisplayList = false;
12791
12792        return more;
12793    }
12794
12795    /**
12796     * Manually render this view (and all of its children) to the given Canvas.
12797     * The view must have already done a full layout before this function is
12798     * called.  When implementing a view, implement
12799     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
12800     * If you do need to override this method, call the superclass version.
12801     *
12802     * @param canvas The Canvas to which the View is rendered.
12803     */
12804    public void draw(Canvas canvas) {
12805        if (ViewDebug.TRACE_HIERARCHY) {
12806            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
12807        }
12808
12809        final int privateFlags = mPrivateFlags;
12810        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
12811                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
12812        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
12813
12814        /*
12815         * Draw traversal performs several drawing steps which must be executed
12816         * in the appropriate order:
12817         *
12818         *      1. Draw the background
12819         *      2. If necessary, save the canvas' layers to prepare for fading
12820         *      3. Draw view's content
12821         *      4. Draw children
12822         *      5. If necessary, draw the fading edges and restore layers
12823         *      6. Draw decorations (scrollbars for instance)
12824         */
12825
12826        // Step 1, draw the background, if needed
12827        int saveCount;
12828
12829        if (!dirtyOpaque) {
12830            final Drawable background = mBackground;
12831            if (background != null) {
12832                final int scrollX = mScrollX;
12833                final int scrollY = mScrollY;
12834
12835                if (mBackgroundSizeChanged) {
12836                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
12837                    mBackgroundSizeChanged = false;
12838                }
12839
12840                if ((scrollX | scrollY) == 0) {
12841                    background.draw(canvas);
12842                } else {
12843                    canvas.translate(scrollX, scrollY);
12844                    background.draw(canvas);
12845                    canvas.translate(-scrollX, -scrollY);
12846                }
12847            }
12848        }
12849
12850        // skip step 2 & 5 if possible (common case)
12851        final int viewFlags = mViewFlags;
12852        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
12853        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
12854        if (!verticalEdges && !horizontalEdges) {
12855            // Step 3, draw the content
12856            if (!dirtyOpaque) onDraw(canvas);
12857
12858            // Step 4, draw the children
12859            dispatchDraw(canvas);
12860
12861            // Step 6, draw decorations (scrollbars)
12862            onDrawScrollBars(canvas);
12863
12864            // we're done...
12865            return;
12866        }
12867
12868        /*
12869         * Here we do the full fledged routine...
12870         * (this is an uncommon case where speed matters less,
12871         * this is why we repeat some of the tests that have been
12872         * done above)
12873         */
12874
12875        boolean drawTop = false;
12876        boolean drawBottom = false;
12877        boolean drawLeft = false;
12878        boolean drawRight = false;
12879
12880        float topFadeStrength = 0.0f;
12881        float bottomFadeStrength = 0.0f;
12882        float leftFadeStrength = 0.0f;
12883        float rightFadeStrength = 0.0f;
12884
12885        // Step 2, save the canvas' layers
12886        int paddingLeft = mPaddingLeft;
12887
12888        final boolean offsetRequired = isPaddingOffsetRequired();
12889        if (offsetRequired) {
12890            paddingLeft += getLeftPaddingOffset();
12891        }
12892
12893        int left = mScrollX + paddingLeft;
12894        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
12895        int top = mScrollY + getFadeTop(offsetRequired);
12896        int bottom = top + getFadeHeight(offsetRequired);
12897
12898        if (offsetRequired) {
12899            right += getRightPaddingOffset();
12900            bottom += getBottomPaddingOffset();
12901        }
12902
12903        final ScrollabilityCache scrollabilityCache = mScrollCache;
12904        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
12905        int length = (int) fadeHeight;
12906
12907        // clip the fade length if top and bottom fades overlap
12908        // overlapping fades produce odd-looking artifacts
12909        if (verticalEdges && (top + length > bottom - length)) {
12910            length = (bottom - top) / 2;
12911        }
12912
12913        // also clip horizontal fades if necessary
12914        if (horizontalEdges && (left + length > right - length)) {
12915            length = (right - left) / 2;
12916        }
12917
12918        if (verticalEdges) {
12919            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
12920            drawTop = topFadeStrength * fadeHeight > 1.0f;
12921            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
12922            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
12923        }
12924
12925        if (horizontalEdges) {
12926            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
12927            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
12928            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
12929            drawRight = rightFadeStrength * fadeHeight > 1.0f;
12930        }
12931
12932        saveCount = canvas.getSaveCount();
12933
12934        int solidColor = getSolidColor();
12935        if (solidColor == 0) {
12936            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
12937
12938            if (drawTop) {
12939                canvas.saveLayer(left, top, right, top + length, null, flags);
12940            }
12941
12942            if (drawBottom) {
12943                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
12944            }
12945
12946            if (drawLeft) {
12947                canvas.saveLayer(left, top, left + length, bottom, null, flags);
12948            }
12949
12950            if (drawRight) {
12951                canvas.saveLayer(right - length, top, right, bottom, null, flags);
12952            }
12953        } else {
12954            scrollabilityCache.setFadeColor(solidColor);
12955        }
12956
12957        // Step 3, draw the content
12958        if (!dirtyOpaque) onDraw(canvas);
12959
12960        // Step 4, draw the children
12961        dispatchDraw(canvas);
12962
12963        // Step 5, draw the fade effect and restore layers
12964        final Paint p = scrollabilityCache.paint;
12965        final Matrix matrix = scrollabilityCache.matrix;
12966        final Shader fade = scrollabilityCache.shader;
12967
12968        if (drawTop) {
12969            matrix.setScale(1, fadeHeight * topFadeStrength);
12970            matrix.postTranslate(left, top);
12971            fade.setLocalMatrix(matrix);
12972            canvas.drawRect(left, top, right, top + length, p);
12973        }
12974
12975        if (drawBottom) {
12976            matrix.setScale(1, fadeHeight * bottomFadeStrength);
12977            matrix.postRotate(180);
12978            matrix.postTranslate(left, bottom);
12979            fade.setLocalMatrix(matrix);
12980            canvas.drawRect(left, bottom - length, right, bottom, p);
12981        }
12982
12983        if (drawLeft) {
12984            matrix.setScale(1, fadeHeight * leftFadeStrength);
12985            matrix.postRotate(-90);
12986            matrix.postTranslate(left, top);
12987            fade.setLocalMatrix(matrix);
12988            canvas.drawRect(left, top, left + length, bottom, p);
12989        }
12990
12991        if (drawRight) {
12992            matrix.setScale(1, fadeHeight * rightFadeStrength);
12993            matrix.postRotate(90);
12994            matrix.postTranslate(right, top);
12995            fade.setLocalMatrix(matrix);
12996            canvas.drawRect(right - length, top, right, bottom, p);
12997        }
12998
12999        canvas.restoreToCount(saveCount);
13000
13001        // Step 6, draw decorations (scrollbars)
13002        onDrawScrollBars(canvas);
13003    }
13004
13005    /**
13006     * Override this if your view is known to always be drawn on top of a solid color background,
13007     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13008     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13009     * should be set to 0xFF.
13010     *
13011     * @see #setVerticalFadingEdgeEnabled(boolean)
13012     * @see #setHorizontalFadingEdgeEnabled(boolean)
13013     *
13014     * @return The known solid color background for this view, or 0 if the color may vary
13015     */
13016    @ViewDebug.ExportedProperty(category = "drawing")
13017    public int getSolidColor() {
13018        return 0;
13019    }
13020
13021    /**
13022     * Build a human readable string representation of the specified view flags.
13023     *
13024     * @param flags the view flags to convert to a string
13025     * @return a String representing the supplied flags
13026     */
13027    private static String printFlags(int flags) {
13028        String output = "";
13029        int numFlags = 0;
13030        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13031            output += "TAKES_FOCUS";
13032            numFlags++;
13033        }
13034
13035        switch (flags & VISIBILITY_MASK) {
13036        case INVISIBLE:
13037            if (numFlags > 0) {
13038                output += " ";
13039            }
13040            output += "INVISIBLE";
13041            // USELESS HERE numFlags++;
13042            break;
13043        case GONE:
13044            if (numFlags > 0) {
13045                output += " ";
13046            }
13047            output += "GONE";
13048            // USELESS HERE numFlags++;
13049            break;
13050        default:
13051            break;
13052        }
13053        return output;
13054    }
13055
13056    /**
13057     * Build a human readable string representation of the specified private
13058     * view flags.
13059     *
13060     * @param privateFlags the private view flags to convert to a string
13061     * @return a String representing the supplied flags
13062     */
13063    private static String printPrivateFlags(int privateFlags) {
13064        String output = "";
13065        int numFlags = 0;
13066
13067        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13068            output += "WANTS_FOCUS";
13069            numFlags++;
13070        }
13071
13072        if ((privateFlags & FOCUSED) == FOCUSED) {
13073            if (numFlags > 0) {
13074                output += " ";
13075            }
13076            output += "FOCUSED";
13077            numFlags++;
13078        }
13079
13080        if ((privateFlags & SELECTED) == SELECTED) {
13081            if (numFlags > 0) {
13082                output += " ";
13083            }
13084            output += "SELECTED";
13085            numFlags++;
13086        }
13087
13088        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13089            if (numFlags > 0) {
13090                output += " ";
13091            }
13092            output += "IS_ROOT_NAMESPACE";
13093            numFlags++;
13094        }
13095
13096        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13097            if (numFlags > 0) {
13098                output += " ";
13099            }
13100            output += "HAS_BOUNDS";
13101            numFlags++;
13102        }
13103
13104        if ((privateFlags & DRAWN) == DRAWN) {
13105            if (numFlags > 0) {
13106                output += " ";
13107            }
13108            output += "DRAWN";
13109            // USELESS HERE numFlags++;
13110        }
13111        return output;
13112    }
13113
13114    /**
13115     * <p>Indicates whether or not this view's layout will be requested during
13116     * the next hierarchy layout pass.</p>
13117     *
13118     * @return true if the layout will be forced during next layout pass
13119     */
13120    public boolean isLayoutRequested() {
13121        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13122    }
13123
13124    /**
13125     * Assign a size and position to a view and all of its
13126     * descendants
13127     *
13128     * <p>This is the second phase of the layout mechanism.
13129     * (The first is measuring). In this phase, each parent calls
13130     * layout on all of its children to position them.
13131     * This is typically done using the child measurements
13132     * that were stored in the measure pass().</p>
13133     *
13134     * <p>Derived classes should not override this method.
13135     * Derived classes with children should override
13136     * onLayout. In that method, they should
13137     * call layout on each of their children.</p>
13138     *
13139     * @param l Left position, relative to parent
13140     * @param t Top position, relative to parent
13141     * @param r Right position, relative to parent
13142     * @param b Bottom position, relative to parent
13143     */
13144    @SuppressWarnings({"unchecked"})
13145    public void layout(int l, int t, int r, int b) {
13146        int oldL = mLeft;
13147        int oldT = mTop;
13148        int oldB = mBottom;
13149        int oldR = mRight;
13150        boolean changed = setFrame(l, t, r, b);
13151        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13152            if (ViewDebug.TRACE_HIERARCHY) {
13153                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
13154            }
13155
13156            onLayout(changed, l, t, r, b);
13157            mPrivateFlags &= ~LAYOUT_REQUIRED;
13158
13159            ListenerInfo li = mListenerInfo;
13160            if (li != null && li.mOnLayoutChangeListeners != null) {
13161                ArrayList<OnLayoutChangeListener> listenersCopy =
13162                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13163                int numListeners = listenersCopy.size();
13164                for (int i = 0; i < numListeners; ++i) {
13165                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13166                }
13167            }
13168        }
13169        mPrivateFlags &= ~FORCE_LAYOUT;
13170    }
13171
13172    /**
13173     * Called from layout when this view should
13174     * assign a size and position to each of its children.
13175     *
13176     * Derived classes with children should override
13177     * this method and call layout on each of
13178     * their children.
13179     * @param changed This is a new size or position for this view
13180     * @param left Left position, relative to parent
13181     * @param top Top position, relative to parent
13182     * @param right Right position, relative to parent
13183     * @param bottom Bottom position, relative to parent
13184     */
13185    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13186    }
13187
13188    /**
13189     * Assign a size and position to this view.
13190     *
13191     * This is called from layout.
13192     *
13193     * @param left Left position, relative to parent
13194     * @param top Top position, relative to parent
13195     * @param right Right position, relative to parent
13196     * @param bottom Bottom position, relative to parent
13197     * @return true if the new size and position are different than the
13198     *         previous ones
13199     * {@hide}
13200     */
13201    protected boolean setFrame(int left, int top, int right, int bottom) {
13202        boolean changed = false;
13203
13204        if (DBG) {
13205            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13206                    + right + "," + bottom + ")");
13207        }
13208
13209        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13210            changed = true;
13211
13212            // Remember our drawn bit
13213            int drawn = mPrivateFlags & DRAWN;
13214
13215            int oldWidth = mRight - mLeft;
13216            int oldHeight = mBottom - mTop;
13217            int newWidth = right - left;
13218            int newHeight = bottom - top;
13219            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13220
13221            // Invalidate our old position
13222            invalidate(sizeChanged);
13223
13224            mLeft = left;
13225            mTop = top;
13226            mRight = right;
13227            mBottom = bottom;
13228            if (mDisplayList != null) {
13229                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13230            }
13231
13232            mPrivateFlags |= HAS_BOUNDS;
13233
13234
13235            if (sizeChanged) {
13236                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13237                    // A change in dimension means an auto-centered pivot point changes, too
13238                    if (mTransformationInfo != null) {
13239                        mTransformationInfo.mMatrixDirty = true;
13240                    }
13241                }
13242                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13243            }
13244
13245            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13246                // If we are visible, force the DRAWN bit to on so that
13247                // this invalidate will go through (at least to our parent).
13248                // This is because someone may have invalidated this view
13249                // before this call to setFrame came in, thereby clearing
13250                // the DRAWN bit.
13251                mPrivateFlags |= DRAWN;
13252                invalidate(sizeChanged);
13253                // parent display list may need to be recreated based on a change in the bounds
13254                // of any child
13255                invalidateParentCaches();
13256            }
13257
13258            // Reset drawn bit to original value (invalidate turns it off)
13259            mPrivateFlags |= drawn;
13260
13261            mBackgroundSizeChanged = true;
13262        }
13263        return changed;
13264    }
13265
13266    /**
13267     * Finalize inflating a view from XML.  This is called as the last phase
13268     * of inflation, after all child views have been added.
13269     *
13270     * <p>Even if the subclass overrides onFinishInflate, they should always be
13271     * sure to call the super method, so that we get called.
13272     */
13273    protected void onFinishInflate() {
13274    }
13275
13276    /**
13277     * Returns the resources associated with this view.
13278     *
13279     * @return Resources object.
13280     */
13281    public Resources getResources() {
13282        return mResources;
13283    }
13284
13285    /**
13286     * Invalidates the specified Drawable.
13287     *
13288     * @param drawable the drawable to invalidate
13289     */
13290    public void invalidateDrawable(Drawable drawable) {
13291        if (verifyDrawable(drawable)) {
13292            final Rect dirty = drawable.getBounds();
13293            final int scrollX = mScrollX;
13294            final int scrollY = mScrollY;
13295
13296            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13297                    dirty.right + scrollX, dirty.bottom + scrollY);
13298        }
13299    }
13300
13301    /**
13302     * Schedules an action on a drawable to occur at a specified time.
13303     *
13304     * @param who the recipient of the action
13305     * @param what the action to run on the drawable
13306     * @param when the time at which the action must occur. Uses the
13307     *        {@link SystemClock#uptimeMillis} timebase.
13308     */
13309    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13310        if (verifyDrawable(who) && what != null) {
13311            final long delay = when - SystemClock.uptimeMillis();
13312            if (mAttachInfo != null) {
13313                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13314                        Choreographer.CALLBACK_ANIMATION, what, who,
13315                        Choreographer.subtractFrameDelay(delay));
13316            } else {
13317                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13318            }
13319        }
13320    }
13321
13322    /**
13323     * Cancels a scheduled action on a drawable.
13324     *
13325     * @param who the recipient of the action
13326     * @param what the action to cancel
13327     */
13328    public void unscheduleDrawable(Drawable who, Runnable what) {
13329        if (verifyDrawable(who) && what != null) {
13330            if (mAttachInfo != null) {
13331                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13332                        Choreographer.CALLBACK_ANIMATION, what, who);
13333            } else {
13334                ViewRootImpl.getRunQueue().removeCallbacks(what);
13335            }
13336        }
13337    }
13338
13339    /**
13340     * Unschedule any events associated with the given Drawable.  This can be
13341     * used when selecting a new Drawable into a view, so that the previous
13342     * one is completely unscheduled.
13343     *
13344     * @param who The Drawable to unschedule.
13345     *
13346     * @see #drawableStateChanged
13347     */
13348    public void unscheduleDrawable(Drawable who) {
13349        if (mAttachInfo != null && who != null) {
13350            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13351                    Choreographer.CALLBACK_ANIMATION, null, who);
13352        }
13353    }
13354
13355    /**
13356    * Return the layout direction of a given Drawable.
13357    *
13358    * @param who the Drawable to query
13359    */
13360    public int getResolvedLayoutDirection(Drawable who) {
13361        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13362    }
13363
13364    /**
13365     * If your view subclass is displaying its own Drawable objects, it should
13366     * override this function and return true for any Drawable it is
13367     * displaying.  This allows animations for those drawables to be
13368     * scheduled.
13369     *
13370     * <p>Be sure to call through to the super class when overriding this
13371     * function.
13372     *
13373     * @param who The Drawable to verify.  Return true if it is one you are
13374     *            displaying, else return the result of calling through to the
13375     *            super class.
13376     *
13377     * @return boolean If true than the Drawable is being displayed in the
13378     *         view; else false and it is not allowed to animate.
13379     *
13380     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13381     * @see #drawableStateChanged()
13382     */
13383    protected boolean verifyDrawable(Drawable who) {
13384        return who == mBackground;
13385    }
13386
13387    /**
13388     * This function is called whenever the state of the view changes in such
13389     * a way that it impacts the state of drawables being shown.
13390     *
13391     * <p>Be sure to call through to the superclass when overriding this
13392     * function.
13393     *
13394     * @see Drawable#setState(int[])
13395     */
13396    protected void drawableStateChanged() {
13397        Drawable d = mBackground;
13398        if (d != null && d.isStateful()) {
13399            d.setState(getDrawableState());
13400        }
13401    }
13402
13403    /**
13404     * Call this to force a view to update its drawable state. This will cause
13405     * drawableStateChanged to be called on this view. Views that are interested
13406     * in the new state should call getDrawableState.
13407     *
13408     * @see #drawableStateChanged
13409     * @see #getDrawableState
13410     */
13411    public void refreshDrawableState() {
13412        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13413        drawableStateChanged();
13414
13415        ViewParent parent = mParent;
13416        if (parent != null) {
13417            parent.childDrawableStateChanged(this);
13418        }
13419    }
13420
13421    /**
13422     * Return an array of resource IDs of the drawable states representing the
13423     * current state of the view.
13424     *
13425     * @return The current drawable state
13426     *
13427     * @see Drawable#setState(int[])
13428     * @see #drawableStateChanged()
13429     * @see #onCreateDrawableState(int)
13430     */
13431    public final int[] getDrawableState() {
13432        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13433            return mDrawableState;
13434        } else {
13435            mDrawableState = onCreateDrawableState(0);
13436            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13437            return mDrawableState;
13438        }
13439    }
13440
13441    /**
13442     * Generate the new {@link android.graphics.drawable.Drawable} state for
13443     * this view. This is called by the view
13444     * system when the cached Drawable state is determined to be invalid.  To
13445     * retrieve the current state, you should use {@link #getDrawableState}.
13446     *
13447     * @param extraSpace if non-zero, this is the number of extra entries you
13448     * would like in the returned array in which you can place your own
13449     * states.
13450     *
13451     * @return Returns an array holding the current {@link Drawable} state of
13452     * the view.
13453     *
13454     * @see #mergeDrawableStates(int[], int[])
13455     */
13456    protected int[] onCreateDrawableState(int extraSpace) {
13457        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13458                mParent instanceof View) {
13459            return ((View) mParent).onCreateDrawableState(extraSpace);
13460        }
13461
13462        int[] drawableState;
13463
13464        int privateFlags = mPrivateFlags;
13465
13466        int viewStateIndex = 0;
13467        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13468        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13469        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13470        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13471        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13472        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13473        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13474                HardwareRenderer.isAvailable()) {
13475            // This is set if HW acceleration is requested, even if the current
13476            // process doesn't allow it.  This is just to allow app preview
13477            // windows to better match their app.
13478            viewStateIndex |= VIEW_STATE_ACCELERATED;
13479        }
13480        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13481
13482        final int privateFlags2 = mPrivateFlags2;
13483        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13484        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13485
13486        drawableState = VIEW_STATE_SETS[viewStateIndex];
13487
13488        //noinspection ConstantIfStatement
13489        if (false) {
13490            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13491            Log.i("View", toString()
13492                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13493                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13494                    + " fo=" + hasFocus()
13495                    + " sl=" + ((privateFlags & SELECTED) != 0)
13496                    + " wf=" + hasWindowFocus()
13497                    + ": " + Arrays.toString(drawableState));
13498        }
13499
13500        if (extraSpace == 0) {
13501            return drawableState;
13502        }
13503
13504        final int[] fullState;
13505        if (drawableState != null) {
13506            fullState = new int[drawableState.length + extraSpace];
13507            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13508        } else {
13509            fullState = new int[extraSpace];
13510        }
13511
13512        return fullState;
13513    }
13514
13515    /**
13516     * Merge your own state values in <var>additionalState</var> into the base
13517     * state values <var>baseState</var> that were returned by
13518     * {@link #onCreateDrawableState(int)}.
13519     *
13520     * @param baseState The base state values returned by
13521     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13522     * own additional state values.
13523     *
13524     * @param additionalState The additional state values you would like
13525     * added to <var>baseState</var>; this array is not modified.
13526     *
13527     * @return As a convenience, the <var>baseState</var> array you originally
13528     * passed into the function is returned.
13529     *
13530     * @see #onCreateDrawableState(int)
13531     */
13532    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13533        final int N = baseState.length;
13534        int i = N - 1;
13535        while (i >= 0 && baseState[i] == 0) {
13536            i--;
13537        }
13538        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13539        return baseState;
13540    }
13541
13542    /**
13543     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13544     * on all Drawable objects associated with this view.
13545     */
13546    public void jumpDrawablesToCurrentState() {
13547        if (mBackground != null) {
13548            mBackground.jumpToCurrentState();
13549        }
13550    }
13551
13552    /**
13553     * Sets the background color for this view.
13554     * @param color the color of the background
13555     */
13556    @RemotableViewMethod
13557    public void setBackgroundColor(int color) {
13558        if (mBackground instanceof ColorDrawable) {
13559            ((ColorDrawable) mBackground).setColor(color);
13560        } else {
13561            setBackground(new ColorDrawable(color));
13562        }
13563    }
13564
13565    /**
13566     * Set the background to a given resource. The resource should refer to
13567     * a Drawable object or 0 to remove the background.
13568     * @param resid The identifier of the resource.
13569     *
13570     * @attr ref android.R.styleable#View_background
13571     */
13572    @RemotableViewMethod
13573    public void setBackgroundResource(int resid) {
13574        if (resid != 0 && resid == mBackgroundResource) {
13575            return;
13576        }
13577
13578        Drawable d= null;
13579        if (resid != 0) {
13580            d = mResources.getDrawable(resid);
13581        }
13582        setBackground(d);
13583
13584        mBackgroundResource = resid;
13585    }
13586
13587    /**
13588     * Set the background to a given Drawable, or remove the background. If the
13589     * background has padding, this View's padding is set to the background's
13590     * padding. However, when a background is removed, this View's padding isn't
13591     * touched. If setting the padding is desired, please use
13592     * {@link #setPadding(int, int, int, int)}.
13593     *
13594     * @param background The Drawable to use as the background, or null to remove the
13595     *        background
13596     */
13597    public void setBackground(Drawable background) {
13598        //noinspection deprecation
13599        setBackgroundDrawable(background);
13600    }
13601
13602    /**
13603     * @deprecated use {@link #setBackground(Drawable)} instead
13604     */
13605    @Deprecated
13606    public void setBackgroundDrawable(Drawable background) {
13607        if (background == mBackground) {
13608            return;
13609        }
13610
13611        boolean requestLayout = false;
13612
13613        mBackgroundResource = 0;
13614
13615        /*
13616         * Regardless of whether we're setting a new background or not, we want
13617         * to clear the previous drawable.
13618         */
13619        if (mBackground != null) {
13620            mBackground.setCallback(null);
13621            unscheduleDrawable(mBackground);
13622        }
13623
13624        if (background != null) {
13625            Rect padding = sThreadLocal.get();
13626            if (padding == null) {
13627                padding = new Rect();
13628                sThreadLocal.set(padding);
13629            }
13630            if (background.getPadding(padding)) {
13631                switch (background.getResolvedLayoutDirectionSelf()) {
13632                    case LAYOUT_DIRECTION_RTL:
13633                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
13634                        break;
13635                    case LAYOUT_DIRECTION_LTR:
13636                    default:
13637                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
13638                }
13639            }
13640
13641            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
13642            // if it has a different minimum size, we should layout again
13643            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
13644                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
13645                requestLayout = true;
13646            }
13647
13648            background.setCallback(this);
13649            if (background.isStateful()) {
13650                background.setState(getDrawableState());
13651            }
13652            background.setVisible(getVisibility() == VISIBLE, false);
13653            mBackground = background;
13654
13655            if ((mPrivateFlags & SKIP_DRAW) != 0) {
13656                mPrivateFlags &= ~SKIP_DRAW;
13657                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
13658                requestLayout = true;
13659            }
13660        } else {
13661            /* Remove the background */
13662            mBackground = null;
13663
13664            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
13665                /*
13666                 * This view ONLY drew the background before and we're removing
13667                 * the background, so now it won't draw anything
13668                 * (hence we SKIP_DRAW)
13669                 */
13670                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
13671                mPrivateFlags |= SKIP_DRAW;
13672            }
13673
13674            /*
13675             * When the background is set, we try to apply its padding to this
13676             * View. When the background is removed, we don't touch this View's
13677             * padding. This is noted in the Javadocs. Hence, we don't need to
13678             * requestLayout(), the invalidate() below is sufficient.
13679             */
13680
13681            // The old background's minimum size could have affected this
13682            // View's layout, so let's requestLayout
13683            requestLayout = true;
13684        }
13685
13686        computeOpaqueFlags();
13687
13688        if (requestLayout) {
13689            requestLayout();
13690        }
13691
13692        mBackgroundSizeChanged = true;
13693        invalidate(true);
13694    }
13695
13696    /**
13697     * Gets the background drawable
13698     *
13699     * @return The drawable used as the background for this view, if any.
13700     *
13701     * @see #setBackground(Drawable)
13702     *
13703     * @attr ref android.R.styleable#View_background
13704     */
13705    public Drawable getBackground() {
13706        return mBackground;
13707    }
13708
13709    /**
13710     * Sets the padding. The view may add on the space required to display
13711     * the scrollbars, depending on the style and visibility of the scrollbars.
13712     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
13713     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
13714     * from the values set in this call.
13715     *
13716     * @attr ref android.R.styleable#View_padding
13717     * @attr ref android.R.styleable#View_paddingBottom
13718     * @attr ref android.R.styleable#View_paddingLeft
13719     * @attr ref android.R.styleable#View_paddingRight
13720     * @attr ref android.R.styleable#View_paddingTop
13721     * @param left the left padding in pixels
13722     * @param top the top padding in pixels
13723     * @param right the right padding in pixels
13724     * @param bottom the bottom padding in pixels
13725     */
13726    public void setPadding(int left, int top, int right, int bottom) {
13727        mUserPaddingStart = -1;
13728        mUserPaddingEnd = -1;
13729        mUserPaddingRelative = false;
13730
13731        internalSetPadding(left, top, right, bottom);
13732    }
13733
13734    private void internalSetPadding(int left, int top, int right, int bottom) {
13735        mUserPaddingLeft = left;
13736        mUserPaddingRight = right;
13737        mUserPaddingBottom = bottom;
13738
13739        final int viewFlags = mViewFlags;
13740        boolean changed = false;
13741
13742        // Common case is there are no scroll bars.
13743        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
13744            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
13745                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
13746                        ? 0 : getVerticalScrollbarWidth();
13747                switch (mVerticalScrollbarPosition) {
13748                    case SCROLLBAR_POSITION_DEFAULT:
13749                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
13750                            left += offset;
13751                        } else {
13752                            right += offset;
13753                        }
13754                        break;
13755                    case SCROLLBAR_POSITION_RIGHT:
13756                        right += offset;
13757                        break;
13758                    case SCROLLBAR_POSITION_LEFT:
13759                        left += offset;
13760                        break;
13761                }
13762            }
13763            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
13764                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
13765                        ? 0 : getHorizontalScrollbarHeight();
13766            }
13767        }
13768
13769        if (mPaddingLeft != left) {
13770            changed = true;
13771            mPaddingLeft = left;
13772        }
13773        if (mPaddingTop != top) {
13774            changed = true;
13775            mPaddingTop = top;
13776        }
13777        if (mPaddingRight != right) {
13778            changed = true;
13779            mPaddingRight = right;
13780        }
13781        if (mPaddingBottom != bottom) {
13782            changed = true;
13783            mPaddingBottom = bottom;
13784        }
13785
13786        if (changed) {
13787            requestLayout();
13788        }
13789    }
13790
13791    /**
13792     * Sets the relative padding. The view may add on the space required to display
13793     * the scrollbars, depending on the style and visibility of the scrollbars.
13794     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
13795     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
13796     * from the values set in this call.
13797     *
13798     * @attr ref android.R.styleable#View_padding
13799     * @attr ref android.R.styleable#View_paddingBottom
13800     * @attr ref android.R.styleable#View_paddingStart
13801     * @attr ref android.R.styleable#View_paddingEnd
13802     * @attr ref android.R.styleable#View_paddingTop
13803     * @param start the start padding in pixels
13804     * @param top the top padding in pixels
13805     * @param end the end padding in pixels
13806     * @param bottom the bottom padding in pixels
13807     */
13808    public void setPaddingRelative(int start, int top, int end, int bottom) {
13809        mUserPaddingStart = start;
13810        mUserPaddingEnd = end;
13811        mUserPaddingRelative = true;
13812
13813        switch(getResolvedLayoutDirection()) {
13814            case LAYOUT_DIRECTION_RTL:
13815                internalSetPadding(end, top, start, bottom);
13816                break;
13817            case LAYOUT_DIRECTION_LTR:
13818            default:
13819                internalSetPadding(start, top, end, bottom);
13820        }
13821    }
13822
13823    /**
13824     * Returns the top padding of this view.
13825     *
13826     * @return the top padding in pixels
13827     */
13828    public int getPaddingTop() {
13829        return mPaddingTop;
13830    }
13831
13832    /**
13833     * Returns the bottom padding of this view. If there are inset and enabled
13834     * scrollbars, this value may include the space required to display the
13835     * scrollbars as well.
13836     *
13837     * @return the bottom padding in pixels
13838     */
13839    public int getPaddingBottom() {
13840        return mPaddingBottom;
13841    }
13842
13843    /**
13844     * Returns the left padding of this view. If there are inset and enabled
13845     * scrollbars, this value may include the space required to display the
13846     * scrollbars as well.
13847     *
13848     * @return the left padding in pixels
13849     */
13850    public int getPaddingLeft() {
13851        return mPaddingLeft;
13852    }
13853
13854    /**
13855     * Returns the start padding of this view depending on its resolved layout direction.
13856     * If there are inset and enabled scrollbars, this value may include the space
13857     * required to display the scrollbars as well.
13858     *
13859     * @return the start padding in pixels
13860     */
13861    public int getPaddingStart() {
13862        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13863                mPaddingRight : mPaddingLeft;
13864    }
13865
13866    /**
13867     * Returns the right padding of this view. If there are inset and enabled
13868     * scrollbars, this value may include the space required to display the
13869     * scrollbars as well.
13870     *
13871     * @return the right padding in pixels
13872     */
13873    public int getPaddingRight() {
13874        return mPaddingRight;
13875    }
13876
13877    /**
13878     * Returns the end padding of this view depending on its resolved layout direction.
13879     * If there are inset and enabled scrollbars, this value may include the space
13880     * required to display the scrollbars as well.
13881     *
13882     * @return the end padding in pixels
13883     */
13884    public int getPaddingEnd() {
13885        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
13886                mPaddingLeft : mPaddingRight;
13887    }
13888
13889    /**
13890     * Return if the padding as been set thru relative values
13891     * {@link #setPaddingRelative(int, int, int, int)} or thru
13892     * @attr ref android.R.styleable#View_paddingStart or
13893     * @attr ref android.R.styleable#View_paddingEnd
13894     *
13895     * @return true if the padding is relative or false if it is not.
13896     */
13897    public boolean isPaddingRelative() {
13898        return mUserPaddingRelative;
13899    }
13900
13901    /**
13902     * @hide
13903     */
13904    public Insets getOpticalInsets() {
13905        if (mLayoutInsets == null) {
13906            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
13907        }
13908        return mLayoutInsets;
13909    }
13910
13911    /**
13912     * @hide
13913     */
13914    public void setLayoutInsets(Insets layoutInsets) {
13915        mLayoutInsets = layoutInsets;
13916    }
13917
13918    /**
13919     * Changes the selection state of this view. A view can be selected or not.
13920     * Note that selection is not the same as focus. Views are typically
13921     * selected in the context of an AdapterView like ListView or GridView;
13922     * the selected view is the view that is highlighted.
13923     *
13924     * @param selected true if the view must be selected, false otherwise
13925     */
13926    public void setSelected(boolean selected) {
13927        if (((mPrivateFlags & SELECTED) != 0) != selected) {
13928            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
13929            if (!selected) resetPressedState();
13930            invalidate(true);
13931            refreshDrawableState();
13932            dispatchSetSelected(selected);
13933            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
13934                notifyAccessibilityStateChanged();
13935            }
13936        }
13937    }
13938
13939    /**
13940     * Dispatch setSelected to all of this View's children.
13941     *
13942     * @see #setSelected(boolean)
13943     *
13944     * @param selected The new selected state
13945     */
13946    protected void dispatchSetSelected(boolean selected) {
13947    }
13948
13949    /**
13950     * Indicates the selection state of this view.
13951     *
13952     * @return true if the view is selected, false otherwise
13953     */
13954    @ViewDebug.ExportedProperty
13955    public boolean isSelected() {
13956        return (mPrivateFlags & SELECTED) != 0;
13957    }
13958
13959    /**
13960     * Changes the activated state of this view. A view can be activated or not.
13961     * Note that activation is not the same as selection.  Selection is
13962     * a transient property, representing the view (hierarchy) the user is
13963     * currently interacting with.  Activation is a longer-term state that the
13964     * user can move views in and out of.  For example, in a list view with
13965     * single or multiple selection enabled, the views in the current selection
13966     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
13967     * here.)  The activated state is propagated down to children of the view it
13968     * is set on.
13969     *
13970     * @param activated true if the view must be activated, false otherwise
13971     */
13972    public void setActivated(boolean activated) {
13973        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
13974            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
13975            invalidate(true);
13976            refreshDrawableState();
13977            dispatchSetActivated(activated);
13978        }
13979    }
13980
13981    /**
13982     * Dispatch setActivated to all of this View's children.
13983     *
13984     * @see #setActivated(boolean)
13985     *
13986     * @param activated The new activated state
13987     */
13988    protected void dispatchSetActivated(boolean activated) {
13989    }
13990
13991    /**
13992     * Indicates the activation state of this view.
13993     *
13994     * @return true if the view is activated, false otherwise
13995     */
13996    @ViewDebug.ExportedProperty
13997    public boolean isActivated() {
13998        return (mPrivateFlags & ACTIVATED) != 0;
13999    }
14000
14001    /**
14002     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14003     * observer can be used to get notifications when global events, like
14004     * layout, happen.
14005     *
14006     * The returned ViewTreeObserver observer is not guaranteed to remain
14007     * valid for the lifetime of this View. If the caller of this method keeps
14008     * a long-lived reference to ViewTreeObserver, it should always check for
14009     * the return value of {@link ViewTreeObserver#isAlive()}.
14010     *
14011     * @return The ViewTreeObserver for this view's hierarchy.
14012     */
14013    public ViewTreeObserver getViewTreeObserver() {
14014        if (mAttachInfo != null) {
14015            return mAttachInfo.mTreeObserver;
14016        }
14017        if (mFloatingTreeObserver == null) {
14018            mFloatingTreeObserver = new ViewTreeObserver();
14019        }
14020        return mFloatingTreeObserver;
14021    }
14022
14023    /**
14024     * <p>Finds the topmost view in the current view hierarchy.</p>
14025     *
14026     * @return the topmost view containing this view
14027     */
14028    public View getRootView() {
14029        if (mAttachInfo != null) {
14030            final View v = mAttachInfo.mRootView;
14031            if (v != null) {
14032                return v;
14033            }
14034        }
14035
14036        View parent = this;
14037
14038        while (parent.mParent != null && parent.mParent instanceof View) {
14039            parent = (View) parent.mParent;
14040        }
14041
14042        return parent;
14043    }
14044
14045    /**
14046     * <p>Computes the coordinates of this view on the screen. The argument
14047     * must be an array of two integers. After the method returns, the array
14048     * contains the x and y location in that order.</p>
14049     *
14050     * @param location an array of two integers in which to hold the coordinates
14051     */
14052    public void getLocationOnScreen(int[] location) {
14053        getLocationInWindow(location);
14054
14055        final AttachInfo info = mAttachInfo;
14056        if (info != null) {
14057            location[0] += info.mWindowLeft;
14058            location[1] += info.mWindowTop;
14059        }
14060    }
14061
14062    /**
14063     * <p>Computes the coordinates of this view in its window. The argument
14064     * must be an array of two integers. After the method returns, the array
14065     * contains the x and y location in that order.</p>
14066     *
14067     * @param location an array of two integers in which to hold the coordinates
14068     */
14069    public void getLocationInWindow(int[] location) {
14070        if (location == null || location.length < 2) {
14071            throw new IllegalArgumentException("location must be an array of two integers");
14072        }
14073
14074        if (mAttachInfo == null) {
14075            // When the view is not attached to a window, this method does not make sense
14076            location[0] = location[1] = 0;
14077            return;
14078        }
14079
14080        float[] position = mAttachInfo.mTmpTransformLocation;
14081        position[0] = position[1] = 0.0f;
14082
14083        if (!hasIdentityMatrix()) {
14084            getMatrix().mapPoints(position);
14085        }
14086
14087        position[0] += mLeft;
14088        position[1] += mTop;
14089
14090        ViewParent viewParent = mParent;
14091        while (viewParent instanceof View) {
14092            final View view = (View) viewParent;
14093
14094            position[0] -= view.mScrollX;
14095            position[1] -= view.mScrollY;
14096
14097            if (!view.hasIdentityMatrix()) {
14098                view.getMatrix().mapPoints(position);
14099            }
14100
14101            position[0] += view.mLeft;
14102            position[1] += view.mTop;
14103
14104            viewParent = view.mParent;
14105         }
14106
14107        if (viewParent instanceof ViewRootImpl) {
14108            // *cough*
14109            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14110            position[1] -= vr.mCurScrollY;
14111        }
14112
14113        location[0] = (int) (position[0] + 0.5f);
14114        location[1] = (int) (position[1] + 0.5f);
14115    }
14116
14117    /**
14118     * {@hide}
14119     * @param id the id of the view to be found
14120     * @return the view of the specified id, null if cannot be found
14121     */
14122    protected View findViewTraversal(int id) {
14123        if (id == mID) {
14124            return this;
14125        }
14126        return null;
14127    }
14128
14129    /**
14130     * {@hide}
14131     * @param tag the tag of the view to be found
14132     * @return the view of specified tag, null if cannot be found
14133     */
14134    protected View findViewWithTagTraversal(Object tag) {
14135        if (tag != null && tag.equals(mTag)) {
14136            return this;
14137        }
14138        return null;
14139    }
14140
14141    /**
14142     * {@hide}
14143     * @param predicate The predicate to evaluate.
14144     * @param childToSkip If not null, ignores this child during the recursive traversal.
14145     * @return The first view that matches the predicate or null.
14146     */
14147    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14148        if (predicate.apply(this)) {
14149            return this;
14150        }
14151        return null;
14152    }
14153
14154    /**
14155     * Look for a child view with the given id.  If this view has the given
14156     * id, return this view.
14157     *
14158     * @param id The id to search for.
14159     * @return The view that has the given id in the hierarchy or null
14160     */
14161    public final View findViewById(int id) {
14162        if (id < 0) {
14163            return null;
14164        }
14165        return findViewTraversal(id);
14166    }
14167
14168    /**
14169     * Finds a view by its unuque and stable accessibility id.
14170     *
14171     * @param accessibilityId The searched accessibility id.
14172     * @return The found view.
14173     */
14174    final View findViewByAccessibilityId(int accessibilityId) {
14175        if (accessibilityId < 0) {
14176            return null;
14177        }
14178        return findViewByAccessibilityIdTraversal(accessibilityId);
14179    }
14180
14181    /**
14182     * Performs the traversal to find a view by its unuque and stable accessibility id.
14183     *
14184     * <strong>Note:</strong>This method does not stop at the root namespace
14185     * boundary since the user can touch the screen at an arbitrary location
14186     * potentially crossing the root namespace bounday which will send an
14187     * accessibility event to accessibility services and they should be able
14188     * to obtain the event source. Also accessibility ids are guaranteed to be
14189     * unique in the window.
14190     *
14191     * @param accessibilityId The accessibility id.
14192     * @return The found view.
14193     */
14194    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14195        if (getAccessibilityViewId() == accessibilityId) {
14196            return this;
14197        }
14198        return null;
14199    }
14200
14201    /**
14202     * Look for a child view with the given tag.  If this view has the given
14203     * tag, return this view.
14204     *
14205     * @param tag The tag to search for, using "tag.equals(getTag())".
14206     * @return The View that has the given tag in the hierarchy or null
14207     */
14208    public final View findViewWithTag(Object tag) {
14209        if (tag == null) {
14210            return null;
14211        }
14212        return findViewWithTagTraversal(tag);
14213    }
14214
14215    /**
14216     * {@hide}
14217     * Look for a child view that matches the specified predicate.
14218     * If this view matches the predicate, return this view.
14219     *
14220     * @param predicate The predicate to evaluate.
14221     * @return The first view that matches the predicate or null.
14222     */
14223    public final View findViewByPredicate(Predicate<View> predicate) {
14224        return findViewByPredicateTraversal(predicate, null);
14225    }
14226
14227    /**
14228     * {@hide}
14229     * Look for a child view that matches the specified predicate,
14230     * starting with the specified view and its descendents and then
14231     * recusively searching the ancestors and siblings of that view
14232     * until this view is reached.
14233     *
14234     * This method is useful in cases where the predicate does not match
14235     * a single unique view (perhaps multiple views use the same id)
14236     * and we are trying to find the view that is "closest" in scope to the
14237     * starting view.
14238     *
14239     * @param start The view to start from.
14240     * @param predicate The predicate to evaluate.
14241     * @return The first view that matches the predicate or null.
14242     */
14243    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14244        View childToSkip = null;
14245        for (;;) {
14246            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14247            if (view != null || start == this) {
14248                return view;
14249            }
14250
14251            ViewParent parent = start.getParent();
14252            if (parent == null || !(parent instanceof View)) {
14253                return null;
14254            }
14255
14256            childToSkip = start;
14257            start = (View) parent;
14258        }
14259    }
14260
14261    /**
14262     * Sets the identifier for this view. The identifier does not have to be
14263     * unique in this view's hierarchy. The identifier should be a positive
14264     * number.
14265     *
14266     * @see #NO_ID
14267     * @see #getId()
14268     * @see #findViewById(int)
14269     *
14270     * @param id a number used to identify the view
14271     *
14272     * @attr ref android.R.styleable#View_id
14273     */
14274    public void setId(int id) {
14275        mID = id;
14276    }
14277
14278    /**
14279     * {@hide}
14280     *
14281     * @param isRoot true if the view belongs to the root namespace, false
14282     *        otherwise
14283     */
14284    public void setIsRootNamespace(boolean isRoot) {
14285        if (isRoot) {
14286            mPrivateFlags |= IS_ROOT_NAMESPACE;
14287        } else {
14288            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14289        }
14290    }
14291
14292    /**
14293     * {@hide}
14294     *
14295     * @return true if the view belongs to the root namespace, false otherwise
14296     */
14297    public boolean isRootNamespace() {
14298        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14299    }
14300
14301    /**
14302     * Returns this view's identifier.
14303     *
14304     * @return a positive integer used to identify the view or {@link #NO_ID}
14305     *         if the view has no ID
14306     *
14307     * @see #setId(int)
14308     * @see #findViewById(int)
14309     * @attr ref android.R.styleable#View_id
14310     */
14311    @ViewDebug.CapturedViewProperty
14312    public int getId() {
14313        return mID;
14314    }
14315
14316    /**
14317     * Returns this view's tag.
14318     *
14319     * @return the Object stored in this view as a tag
14320     *
14321     * @see #setTag(Object)
14322     * @see #getTag(int)
14323     */
14324    @ViewDebug.ExportedProperty
14325    public Object getTag() {
14326        return mTag;
14327    }
14328
14329    /**
14330     * Sets the tag associated with this view. A tag can be used to mark
14331     * a view in its hierarchy and does not have to be unique within the
14332     * hierarchy. Tags can also be used to store data within a view without
14333     * resorting to another data structure.
14334     *
14335     * @param tag an Object to tag the view with
14336     *
14337     * @see #getTag()
14338     * @see #setTag(int, Object)
14339     */
14340    public void setTag(final Object tag) {
14341        mTag = tag;
14342    }
14343
14344    /**
14345     * Returns the tag associated with this view and the specified key.
14346     *
14347     * @param key The key identifying the tag
14348     *
14349     * @return the Object stored in this view as a tag
14350     *
14351     * @see #setTag(int, Object)
14352     * @see #getTag()
14353     */
14354    public Object getTag(int key) {
14355        if (mKeyedTags != null) return mKeyedTags.get(key);
14356        return null;
14357    }
14358
14359    /**
14360     * Sets a tag associated with this view and a key. A tag can be used
14361     * to mark a view in its hierarchy and does not have to be unique within
14362     * the hierarchy. Tags can also be used to store data within a view
14363     * without resorting to another data structure.
14364     *
14365     * The specified key should be an id declared in the resources of the
14366     * application to ensure it is unique (see the <a
14367     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14368     * Keys identified as belonging to
14369     * the Android framework or not associated with any package will cause
14370     * an {@link IllegalArgumentException} to be thrown.
14371     *
14372     * @param key The key identifying the tag
14373     * @param tag An Object to tag the view with
14374     *
14375     * @throws IllegalArgumentException If they specified key is not valid
14376     *
14377     * @see #setTag(Object)
14378     * @see #getTag(int)
14379     */
14380    public void setTag(int key, final Object tag) {
14381        // If the package id is 0x00 or 0x01, it's either an undefined package
14382        // or a framework id
14383        if ((key >>> 24) < 2) {
14384            throw new IllegalArgumentException("The key must be an application-specific "
14385                    + "resource id.");
14386        }
14387
14388        setKeyedTag(key, tag);
14389    }
14390
14391    /**
14392     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14393     * framework id.
14394     *
14395     * @hide
14396     */
14397    public void setTagInternal(int key, Object tag) {
14398        if ((key >>> 24) != 0x1) {
14399            throw new IllegalArgumentException("The key must be a framework-specific "
14400                    + "resource id.");
14401        }
14402
14403        setKeyedTag(key, tag);
14404    }
14405
14406    private void setKeyedTag(int key, Object tag) {
14407        if (mKeyedTags == null) {
14408            mKeyedTags = new SparseArray<Object>();
14409        }
14410
14411        mKeyedTags.put(key, tag);
14412    }
14413
14414    /**
14415     * @param consistency The type of consistency. See ViewDebug for more information.
14416     *
14417     * @hide
14418     */
14419    protected boolean dispatchConsistencyCheck(int consistency) {
14420        return onConsistencyCheck(consistency);
14421    }
14422
14423    /**
14424     * Method that subclasses should implement to check their consistency. The type of
14425     * consistency check is indicated by the bit field passed as a parameter.
14426     *
14427     * @param consistency The type of consistency. See ViewDebug for more information.
14428     *
14429     * @throws IllegalStateException if the view is in an inconsistent state.
14430     *
14431     * @hide
14432     */
14433    protected boolean onConsistencyCheck(int consistency) {
14434        boolean result = true;
14435
14436        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
14437        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
14438
14439        if (checkLayout) {
14440            if (getParent() == null) {
14441                result = false;
14442                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14443                        "View " + this + " does not have a parent.");
14444            }
14445
14446            if (mAttachInfo == null) {
14447                result = false;
14448                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14449                        "View " + this + " is not attached to a window.");
14450            }
14451        }
14452
14453        if (checkDrawing) {
14454            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
14455            // from their draw() method
14456
14457            if ((mPrivateFlags & DRAWN) != DRAWN &&
14458                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
14459                result = false;
14460                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
14461                        "View " + this + " was invalidated but its drawing cache is valid.");
14462            }
14463        }
14464
14465        return result;
14466    }
14467
14468    /**
14469     * Prints information about this view in the log output, with the tag
14470     * {@link #VIEW_LOG_TAG}.
14471     *
14472     * @hide
14473     */
14474    public void debug() {
14475        debug(0);
14476    }
14477
14478    /**
14479     * Prints information about this view in the log output, with the tag
14480     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14481     * indentation defined by the <code>depth</code>.
14482     *
14483     * @param depth the indentation level
14484     *
14485     * @hide
14486     */
14487    protected void debug(int depth) {
14488        String output = debugIndent(depth - 1);
14489
14490        output += "+ " + this;
14491        int id = getId();
14492        if (id != -1) {
14493            output += " (id=" + id + ")";
14494        }
14495        Object tag = getTag();
14496        if (tag != null) {
14497            output += " (tag=" + tag + ")";
14498        }
14499        Log.d(VIEW_LOG_TAG, output);
14500
14501        if ((mPrivateFlags & FOCUSED) != 0) {
14502            output = debugIndent(depth) + " FOCUSED";
14503            Log.d(VIEW_LOG_TAG, output);
14504        }
14505
14506        output = debugIndent(depth);
14507        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14508                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14509                + "} ";
14510        Log.d(VIEW_LOG_TAG, output);
14511
14512        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14513                || mPaddingBottom != 0) {
14514            output = debugIndent(depth);
14515            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14516                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14517            Log.d(VIEW_LOG_TAG, output);
14518        }
14519
14520        output = debugIndent(depth);
14521        output += "mMeasureWidth=" + mMeasuredWidth +
14522                " mMeasureHeight=" + mMeasuredHeight;
14523        Log.d(VIEW_LOG_TAG, output);
14524
14525        output = debugIndent(depth);
14526        if (mLayoutParams == null) {
14527            output += "BAD! no layout params";
14528        } else {
14529            output = mLayoutParams.debug(output);
14530        }
14531        Log.d(VIEW_LOG_TAG, output);
14532
14533        output = debugIndent(depth);
14534        output += "flags={";
14535        output += View.printFlags(mViewFlags);
14536        output += "}";
14537        Log.d(VIEW_LOG_TAG, output);
14538
14539        output = debugIndent(depth);
14540        output += "privateFlags={";
14541        output += View.printPrivateFlags(mPrivateFlags);
14542        output += "}";
14543        Log.d(VIEW_LOG_TAG, output);
14544    }
14545
14546    /**
14547     * Creates a string of whitespaces used for indentation.
14548     *
14549     * @param depth the indentation level
14550     * @return a String containing (depth * 2 + 3) * 2 white spaces
14551     *
14552     * @hide
14553     */
14554    protected static String debugIndent(int depth) {
14555        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14556        for (int i = 0; i < (depth * 2) + 3; i++) {
14557            spaces.append(' ').append(' ');
14558        }
14559        return spaces.toString();
14560    }
14561
14562    /**
14563     * <p>Return the offset of the widget's text baseline from the widget's top
14564     * boundary. If this widget does not support baseline alignment, this
14565     * method returns -1. </p>
14566     *
14567     * @return the offset of the baseline within the widget's bounds or -1
14568     *         if baseline alignment is not supported
14569     */
14570    @ViewDebug.ExportedProperty(category = "layout")
14571    public int getBaseline() {
14572        return -1;
14573    }
14574
14575    /**
14576     * Call this when something has changed which has invalidated the
14577     * layout of this view. This will schedule a layout pass of the view
14578     * tree.
14579     */
14580    public void requestLayout() {
14581        if (ViewDebug.TRACE_HIERARCHY) {
14582            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
14583        }
14584
14585        mPrivateFlags |= FORCE_LAYOUT;
14586        mPrivateFlags |= INVALIDATED;
14587
14588        if (mLayoutParams != null) {
14589            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14590        }
14591
14592        if (mParent != null && !mParent.isLayoutRequested()) {
14593            mParent.requestLayout();
14594        }
14595    }
14596
14597    /**
14598     * Forces this view to be laid out during the next layout pass.
14599     * This method does not call requestLayout() or forceLayout()
14600     * on the parent.
14601     */
14602    public void forceLayout() {
14603        mPrivateFlags |= FORCE_LAYOUT;
14604        mPrivateFlags |= INVALIDATED;
14605    }
14606
14607    /**
14608     * <p>
14609     * This is called to find out how big a view should be. The parent
14610     * supplies constraint information in the width and height parameters.
14611     * </p>
14612     *
14613     * <p>
14614     * The actual measurement work of a view is performed in
14615     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14616     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14617     * </p>
14618     *
14619     *
14620     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14621     *        parent
14622     * @param heightMeasureSpec Vertical space requirements as imposed by the
14623     *        parent
14624     *
14625     * @see #onMeasure(int, int)
14626     */
14627    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14628        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14629                widthMeasureSpec != mOldWidthMeasureSpec ||
14630                heightMeasureSpec != mOldHeightMeasureSpec) {
14631
14632            // first clears the measured dimension flag
14633            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14634
14635            if (ViewDebug.TRACE_HIERARCHY) {
14636                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
14637            }
14638
14639            // measure ourselves, this should set the measured dimension flag back
14640            onMeasure(widthMeasureSpec, heightMeasureSpec);
14641
14642            // flag not set, setMeasuredDimension() was not invoked, we raise
14643            // an exception to warn the developer
14644            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14645                throw new IllegalStateException("onMeasure() did not set the"
14646                        + " measured dimension by calling"
14647                        + " setMeasuredDimension()");
14648            }
14649
14650            mPrivateFlags |= LAYOUT_REQUIRED;
14651        }
14652
14653        mOldWidthMeasureSpec = widthMeasureSpec;
14654        mOldHeightMeasureSpec = heightMeasureSpec;
14655    }
14656
14657    /**
14658     * <p>
14659     * Measure the view and its content to determine the measured width and the
14660     * measured height. This method is invoked by {@link #measure(int, int)} and
14661     * should be overriden by subclasses to provide accurate and efficient
14662     * measurement of their contents.
14663     * </p>
14664     *
14665     * <p>
14666     * <strong>CONTRACT:</strong> When overriding this method, you
14667     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14668     * measured width and height of this view. Failure to do so will trigger an
14669     * <code>IllegalStateException</code>, thrown by
14670     * {@link #measure(int, int)}. Calling the superclass'
14671     * {@link #onMeasure(int, int)} is a valid use.
14672     * </p>
14673     *
14674     * <p>
14675     * The base class implementation of measure defaults to the background size,
14676     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14677     * override {@link #onMeasure(int, int)} to provide better measurements of
14678     * their content.
14679     * </p>
14680     *
14681     * <p>
14682     * If this method is overridden, it is the subclass's responsibility to make
14683     * sure the measured height and width are at least the view's minimum height
14684     * and width ({@link #getSuggestedMinimumHeight()} and
14685     * {@link #getSuggestedMinimumWidth()}).
14686     * </p>
14687     *
14688     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
14689     *                         The requirements are encoded with
14690     *                         {@link android.view.View.MeasureSpec}.
14691     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
14692     *                         The requirements are encoded with
14693     *                         {@link android.view.View.MeasureSpec}.
14694     *
14695     * @see #getMeasuredWidth()
14696     * @see #getMeasuredHeight()
14697     * @see #setMeasuredDimension(int, int)
14698     * @see #getSuggestedMinimumHeight()
14699     * @see #getSuggestedMinimumWidth()
14700     * @see android.view.View.MeasureSpec#getMode(int)
14701     * @see android.view.View.MeasureSpec#getSize(int)
14702     */
14703    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
14704        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
14705                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
14706    }
14707
14708    /**
14709     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
14710     * measured width and measured height. Failing to do so will trigger an
14711     * exception at measurement time.</p>
14712     *
14713     * @param measuredWidth The measured width of this view.  May be a complex
14714     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14715     * {@link #MEASURED_STATE_TOO_SMALL}.
14716     * @param measuredHeight The measured height of this view.  May be a complex
14717     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
14718     * {@link #MEASURED_STATE_TOO_SMALL}.
14719     */
14720    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14721        mMeasuredWidth = measuredWidth;
14722        mMeasuredHeight = measuredHeight;
14723
14724        mPrivateFlags |= MEASURED_DIMENSION_SET;
14725    }
14726
14727    /**
14728     * Merge two states as returned by {@link #getMeasuredState()}.
14729     * @param curState The current state as returned from a view or the result
14730     * of combining multiple views.
14731     * @param newState The new view state to combine.
14732     * @return Returns a new integer reflecting the combination of the two
14733     * states.
14734     */
14735    public static int combineMeasuredStates(int curState, int newState) {
14736        return curState | newState;
14737    }
14738
14739    /**
14740     * Version of {@link #resolveSizeAndState(int, int, int)}
14741     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
14742     */
14743    public static int resolveSize(int size, int measureSpec) {
14744        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
14745    }
14746
14747    /**
14748     * Utility to reconcile a desired size and state, with constraints imposed
14749     * by a MeasureSpec.  Will take the desired size, unless a different size
14750     * is imposed by the constraints.  The returned value is a compound integer,
14751     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
14752     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
14753     * size is smaller than the size the view wants to be.
14754     *
14755     * @param size How big the view wants to be
14756     * @param measureSpec Constraints imposed by the parent
14757     * @return Size information bit mask as defined by
14758     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
14759     */
14760    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
14761        int result = size;
14762        int specMode = MeasureSpec.getMode(measureSpec);
14763        int specSize =  MeasureSpec.getSize(measureSpec);
14764        switch (specMode) {
14765        case MeasureSpec.UNSPECIFIED:
14766            result = size;
14767            break;
14768        case MeasureSpec.AT_MOST:
14769            if (specSize < size) {
14770                result = specSize | MEASURED_STATE_TOO_SMALL;
14771            } else {
14772                result = size;
14773            }
14774            break;
14775        case MeasureSpec.EXACTLY:
14776            result = specSize;
14777            break;
14778        }
14779        return result | (childMeasuredState&MEASURED_STATE_MASK);
14780    }
14781
14782    /**
14783     * Utility to return a default size. Uses the supplied size if the
14784     * MeasureSpec imposed no constraints. Will get larger if allowed
14785     * by the MeasureSpec.
14786     *
14787     * @param size Default size for this view
14788     * @param measureSpec Constraints imposed by the parent
14789     * @return The size this view should be.
14790     */
14791    public static int getDefaultSize(int size, int measureSpec) {
14792        int result = size;
14793        int specMode = MeasureSpec.getMode(measureSpec);
14794        int specSize = MeasureSpec.getSize(measureSpec);
14795
14796        switch (specMode) {
14797        case MeasureSpec.UNSPECIFIED:
14798            result = size;
14799            break;
14800        case MeasureSpec.AT_MOST:
14801        case MeasureSpec.EXACTLY:
14802            result = specSize;
14803            break;
14804        }
14805        return result;
14806    }
14807
14808    /**
14809     * Returns the suggested minimum height that the view should use. This
14810     * returns the maximum of the view's minimum height
14811     * and the background's minimum height
14812     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
14813     * <p>
14814     * When being used in {@link #onMeasure(int, int)}, the caller should still
14815     * ensure the returned height is within the requirements of the parent.
14816     *
14817     * @return The suggested minimum height of the view.
14818     */
14819    protected int getSuggestedMinimumHeight() {
14820        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
14821
14822    }
14823
14824    /**
14825     * Returns the suggested minimum width that the view should use. This
14826     * returns the maximum of the view's minimum width)
14827     * and the background's minimum width
14828     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
14829     * <p>
14830     * When being used in {@link #onMeasure(int, int)}, the caller should still
14831     * ensure the returned width is within the requirements of the parent.
14832     *
14833     * @return The suggested minimum width of the view.
14834     */
14835    protected int getSuggestedMinimumWidth() {
14836        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
14837    }
14838
14839    /**
14840     * Returns the minimum height of the view.
14841     *
14842     * @return the minimum height the view will try to be.
14843     *
14844     * @see #setMinimumHeight(int)
14845     *
14846     * @attr ref android.R.styleable#View_minHeight
14847     */
14848    public int getMinimumHeight() {
14849        return mMinHeight;
14850    }
14851
14852    /**
14853     * Sets the minimum height of the view. It is not guaranteed the view will
14854     * be able to achieve this minimum height (for example, if its parent layout
14855     * constrains it with less available height).
14856     *
14857     * @param minHeight The minimum height the view will try to be.
14858     *
14859     * @see #getMinimumHeight()
14860     *
14861     * @attr ref android.R.styleable#View_minHeight
14862     */
14863    public void setMinimumHeight(int minHeight) {
14864        mMinHeight = minHeight;
14865        requestLayout();
14866    }
14867
14868    /**
14869     * Returns the minimum width of the view.
14870     *
14871     * @return the minimum width the view will try to be.
14872     *
14873     * @see #setMinimumWidth(int)
14874     *
14875     * @attr ref android.R.styleable#View_minWidth
14876     */
14877    public int getMinimumWidth() {
14878        return mMinWidth;
14879    }
14880
14881    /**
14882     * Sets the minimum width of the view. It is not guaranteed the view will
14883     * be able to achieve this minimum width (for example, if its parent layout
14884     * constrains it with less available width).
14885     *
14886     * @param minWidth The minimum width the view will try to be.
14887     *
14888     * @see #getMinimumWidth()
14889     *
14890     * @attr ref android.R.styleable#View_minWidth
14891     */
14892    public void setMinimumWidth(int minWidth) {
14893        mMinWidth = minWidth;
14894        requestLayout();
14895
14896    }
14897
14898    /**
14899     * Get the animation currently associated with this view.
14900     *
14901     * @return The animation that is currently playing or
14902     *         scheduled to play for this view.
14903     */
14904    public Animation getAnimation() {
14905        return mCurrentAnimation;
14906    }
14907
14908    /**
14909     * Start the specified animation now.
14910     *
14911     * @param animation the animation to start now
14912     */
14913    public void startAnimation(Animation animation) {
14914        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
14915        setAnimation(animation);
14916        invalidateParentCaches();
14917        invalidate(true);
14918    }
14919
14920    /**
14921     * Cancels any animations for this view.
14922     */
14923    public void clearAnimation() {
14924        if (mCurrentAnimation != null) {
14925            mCurrentAnimation.detach();
14926        }
14927        mCurrentAnimation = null;
14928        invalidateParentIfNeeded();
14929    }
14930
14931    /**
14932     * Sets the next animation to play for this view.
14933     * If you want the animation to play immediately, use
14934     * startAnimation. This method provides allows fine-grained
14935     * control over the start time and invalidation, but you
14936     * must make sure that 1) the animation has a start time set, and
14937     * 2) the view will be invalidated when the animation is supposed to
14938     * start.
14939     *
14940     * @param animation The next animation, or null.
14941     */
14942    public void setAnimation(Animation animation) {
14943        mCurrentAnimation = animation;
14944
14945        if (animation != null) {
14946            // If the screen is off assume the animation start time is now instead of
14947            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
14948            // would cause the animation to start when the screen turns back on
14949            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
14950                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
14951                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
14952            }
14953            animation.reset();
14954        }
14955    }
14956
14957    /**
14958     * Invoked by a parent ViewGroup to notify the start of the animation
14959     * currently associated with this view. If you override this method,
14960     * always call super.onAnimationStart();
14961     *
14962     * @see #setAnimation(android.view.animation.Animation)
14963     * @see #getAnimation()
14964     */
14965    protected void onAnimationStart() {
14966        mPrivateFlags |= ANIMATION_STARTED;
14967    }
14968
14969    /**
14970     * Invoked by a parent ViewGroup to notify the end of the animation
14971     * currently associated with this view. If you override this method,
14972     * always call super.onAnimationEnd();
14973     *
14974     * @see #setAnimation(android.view.animation.Animation)
14975     * @see #getAnimation()
14976     */
14977    protected void onAnimationEnd() {
14978        mPrivateFlags &= ~ANIMATION_STARTED;
14979    }
14980
14981    /**
14982     * Invoked if there is a Transform that involves alpha. Subclass that can
14983     * draw themselves with the specified alpha should return true, and then
14984     * respect that alpha when their onDraw() is called. If this returns false
14985     * then the view may be redirected to draw into an offscreen buffer to
14986     * fulfill the request, which will look fine, but may be slower than if the
14987     * subclass handles it internally. The default implementation returns false.
14988     *
14989     * @param alpha The alpha (0..255) to apply to the view's drawing
14990     * @return true if the view can draw with the specified alpha.
14991     */
14992    protected boolean onSetAlpha(int alpha) {
14993        return false;
14994    }
14995
14996    /**
14997     * This is used by the RootView to perform an optimization when
14998     * the view hierarchy contains one or several SurfaceView.
14999     * SurfaceView is always considered transparent, but its children are not,
15000     * therefore all View objects remove themselves from the global transparent
15001     * region (passed as a parameter to this function).
15002     *
15003     * @param region The transparent region for this ViewAncestor (window).
15004     *
15005     * @return Returns true if the effective visibility of the view at this
15006     * point is opaque, regardless of the transparent region; returns false
15007     * if it is possible for underlying windows to be seen behind the view.
15008     *
15009     * {@hide}
15010     */
15011    public boolean gatherTransparentRegion(Region region) {
15012        final AttachInfo attachInfo = mAttachInfo;
15013        if (region != null && attachInfo != null) {
15014            final int pflags = mPrivateFlags;
15015            if ((pflags & SKIP_DRAW) == 0) {
15016                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15017                // remove it from the transparent region.
15018                final int[] location = attachInfo.mTransparentLocation;
15019                getLocationInWindow(location);
15020                region.op(location[0], location[1], location[0] + mRight - mLeft,
15021                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15022            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15023                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15024                // exists, so we remove the background drawable's non-transparent
15025                // parts from this transparent region.
15026                applyDrawableToTransparentRegion(mBackground, region);
15027            }
15028        }
15029        return true;
15030    }
15031
15032    /**
15033     * Play a sound effect for this view.
15034     *
15035     * <p>The framework will play sound effects for some built in actions, such as
15036     * clicking, but you may wish to play these effects in your widget,
15037     * for instance, for internal navigation.
15038     *
15039     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15040     * {@link #isSoundEffectsEnabled()} is true.
15041     *
15042     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15043     */
15044    public void playSoundEffect(int soundConstant) {
15045        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15046            return;
15047        }
15048        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15049    }
15050
15051    /**
15052     * BZZZTT!!1!
15053     *
15054     * <p>Provide haptic feedback to the user for this view.
15055     *
15056     * <p>The framework will provide haptic feedback for some built in actions,
15057     * such as long presses, but you may wish to provide feedback for your
15058     * own widget.
15059     *
15060     * <p>The feedback will only be performed if
15061     * {@link #isHapticFeedbackEnabled()} is true.
15062     *
15063     * @param feedbackConstant One of the constants defined in
15064     * {@link HapticFeedbackConstants}
15065     */
15066    public boolean performHapticFeedback(int feedbackConstant) {
15067        return performHapticFeedback(feedbackConstant, 0);
15068    }
15069
15070    /**
15071     * BZZZTT!!1!
15072     *
15073     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15074     *
15075     * @param feedbackConstant One of the constants defined in
15076     * {@link HapticFeedbackConstants}
15077     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15078     */
15079    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15080        if (mAttachInfo == null) {
15081            return false;
15082        }
15083        //noinspection SimplifiableIfStatement
15084        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15085                && !isHapticFeedbackEnabled()) {
15086            return false;
15087        }
15088        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15089                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15090    }
15091
15092    /**
15093     * Request that the visibility of the status bar or other screen/window
15094     * decorations be changed.
15095     *
15096     * <p>This method is used to put the over device UI into temporary modes
15097     * where the user's attention is focused more on the application content,
15098     * by dimming or hiding surrounding system affordances.  This is typically
15099     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15100     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15101     * to be placed behind the action bar (and with these flags other system
15102     * affordances) so that smooth transitions between hiding and showing them
15103     * can be done.
15104     *
15105     * <p>Two representative examples of the use of system UI visibility is
15106     * implementing a content browsing application (like a magazine reader)
15107     * and a video playing application.
15108     *
15109     * <p>The first code shows a typical implementation of a View in a content
15110     * browsing application.  In this implementation, the application goes
15111     * into a content-oriented mode by hiding the status bar and action bar,
15112     * and putting the navigation elements into lights out mode.  The user can
15113     * then interact with content while in this mode.  Such an application should
15114     * provide an easy way for the user to toggle out of the mode (such as to
15115     * check information in the status bar or access notifications).  In the
15116     * implementation here, this is done simply by tapping on the content.
15117     *
15118     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15119     *      content}
15120     *
15121     * <p>This second code sample shows a typical implementation of a View
15122     * in a video playing application.  In this situation, while the video is
15123     * playing the application would like to go into a complete full-screen mode,
15124     * to use as much of the display as possible for the video.  When in this state
15125     * the user can not interact with the application; the system intercepts
15126     * touching on the screen to pop the UI out of full screen mode.
15127     *
15128     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15129     *      content}
15130     *
15131     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15132     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15133     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15134     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15135     */
15136    public void setSystemUiVisibility(int visibility) {
15137        if (visibility != mSystemUiVisibility) {
15138            mSystemUiVisibility = visibility;
15139            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15140                mParent.recomputeViewAttributes(this);
15141            }
15142        }
15143    }
15144
15145    /**
15146     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15147     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15148     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15149     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15150     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15151     */
15152    public int getSystemUiVisibility() {
15153        return mSystemUiVisibility;
15154    }
15155
15156    /**
15157     * Returns the current system UI visibility that is currently set for
15158     * the entire window.  This is the combination of the
15159     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15160     * views in the window.
15161     */
15162    public int getWindowSystemUiVisibility() {
15163        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15164    }
15165
15166    /**
15167     * Override to find out when the window's requested system UI visibility
15168     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15169     * This is different from the callbacks recieved through
15170     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15171     * in that this is only telling you about the local request of the window,
15172     * not the actual values applied by the system.
15173     */
15174    public void onWindowSystemUiVisibilityChanged(int visible) {
15175    }
15176
15177    /**
15178     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15179     * the view hierarchy.
15180     */
15181    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15182        onWindowSystemUiVisibilityChanged(visible);
15183    }
15184
15185    /**
15186     * Set a listener to receive callbacks when the visibility of the system bar changes.
15187     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15188     */
15189    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15190        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15191        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15192            mParent.recomputeViewAttributes(this);
15193        }
15194    }
15195
15196    /**
15197     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15198     * the view hierarchy.
15199     */
15200    public void dispatchSystemUiVisibilityChanged(int visibility) {
15201        ListenerInfo li = mListenerInfo;
15202        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15203            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15204                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15205        }
15206    }
15207
15208    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
15209        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15210        if (val != mSystemUiVisibility) {
15211            setSystemUiVisibility(val);
15212        }
15213    }
15214
15215    /** @hide */
15216    public void setDisabledSystemUiVisibility(int flags) {
15217        if (mAttachInfo != null) {
15218            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15219                mAttachInfo.mDisabledSystemUiVisibility = flags;
15220                if (mParent != null) {
15221                    mParent.recomputeViewAttributes(this);
15222                }
15223            }
15224        }
15225    }
15226
15227    /**
15228     * Creates an image that the system displays during the drag and drop
15229     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15230     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15231     * appearance as the given View. The default also positions the center of the drag shadow
15232     * directly under the touch point. If no View is provided (the constructor with no parameters
15233     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15234     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15235     * default is an invisible drag shadow.
15236     * <p>
15237     * You are not required to use the View you provide to the constructor as the basis of the
15238     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15239     * anything you want as the drag shadow.
15240     * </p>
15241     * <p>
15242     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15243     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15244     *  size and position of the drag shadow. It uses this data to construct a
15245     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15246     *  so that your application can draw the shadow image in the Canvas.
15247     * </p>
15248     *
15249     * <div class="special reference">
15250     * <h3>Developer Guides</h3>
15251     * <p>For a guide to implementing drag and drop features, read the
15252     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15253     * </div>
15254     */
15255    public static class DragShadowBuilder {
15256        private final WeakReference<View> mView;
15257
15258        /**
15259         * Constructs a shadow image builder based on a View. By default, the resulting drag
15260         * shadow will have the same appearance and dimensions as the View, with the touch point
15261         * over the center of the View.
15262         * @param view A View. Any View in scope can be used.
15263         */
15264        public DragShadowBuilder(View view) {
15265            mView = new WeakReference<View>(view);
15266        }
15267
15268        /**
15269         * Construct a shadow builder object with no associated View.  This
15270         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15271         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15272         * to supply the drag shadow's dimensions and appearance without
15273         * reference to any View object. If they are not overridden, then the result is an
15274         * invisible drag shadow.
15275         */
15276        public DragShadowBuilder() {
15277            mView = new WeakReference<View>(null);
15278        }
15279
15280        /**
15281         * Returns the View object that had been passed to the
15282         * {@link #View.DragShadowBuilder(View)}
15283         * constructor.  If that View parameter was {@code null} or if the
15284         * {@link #View.DragShadowBuilder()}
15285         * constructor was used to instantiate the builder object, this method will return
15286         * null.
15287         *
15288         * @return The View object associate with this builder object.
15289         */
15290        @SuppressWarnings({"JavadocReference"})
15291        final public View getView() {
15292            return mView.get();
15293        }
15294
15295        /**
15296         * Provides the metrics for the shadow image. These include the dimensions of
15297         * the shadow image, and the point within that shadow that should
15298         * be centered under the touch location while dragging.
15299         * <p>
15300         * The default implementation sets the dimensions of the shadow to be the
15301         * same as the dimensions of the View itself and centers the shadow under
15302         * the touch point.
15303         * </p>
15304         *
15305         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15306         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15307         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15308         * image.
15309         *
15310         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15311         * shadow image that should be underneath the touch point during the drag and drop
15312         * operation. Your application must set {@link android.graphics.Point#x} to the
15313         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15314         */
15315        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15316            final View view = mView.get();
15317            if (view != null) {
15318                shadowSize.set(view.getWidth(), view.getHeight());
15319                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15320            } else {
15321                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15322            }
15323        }
15324
15325        /**
15326         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15327         * based on the dimensions it received from the
15328         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15329         *
15330         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15331         */
15332        public void onDrawShadow(Canvas canvas) {
15333            final View view = mView.get();
15334            if (view != null) {
15335                view.draw(canvas);
15336            } else {
15337                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15338            }
15339        }
15340    }
15341
15342    /**
15343     * Starts a drag and drop operation. When your application calls this method, it passes a
15344     * {@link android.view.View.DragShadowBuilder} object to the system. The
15345     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15346     * to get metrics for the drag shadow, and then calls the object's
15347     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15348     * <p>
15349     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15350     *  drag events to all the View objects in your application that are currently visible. It does
15351     *  this either by calling the View object's drag listener (an implementation of
15352     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15353     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15354     *  Both are passed a {@link android.view.DragEvent} object that has a
15355     *  {@link android.view.DragEvent#getAction()} value of
15356     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15357     * </p>
15358     * <p>
15359     * Your application can invoke startDrag() on any attached View object. The View object does not
15360     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15361     * be related to the View the user selected for dragging.
15362     * </p>
15363     * @param data A {@link android.content.ClipData} object pointing to the data to be
15364     * transferred by the drag and drop operation.
15365     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15366     * drag shadow.
15367     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15368     * drop operation. This Object is put into every DragEvent object sent by the system during the
15369     * current drag.
15370     * <p>
15371     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15372     * to the target Views. For example, it can contain flags that differentiate between a
15373     * a copy operation and a move operation.
15374     * </p>
15375     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15376     * so the parameter should be set to 0.
15377     * @return {@code true} if the method completes successfully, or
15378     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15379     * do a drag, and so no drag operation is in progress.
15380     */
15381    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15382            Object myLocalState, int flags) {
15383        if (ViewDebug.DEBUG_DRAG) {
15384            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15385        }
15386        boolean okay = false;
15387
15388        Point shadowSize = new Point();
15389        Point shadowTouchPoint = new Point();
15390        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15391
15392        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15393                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15394            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15395        }
15396
15397        if (ViewDebug.DEBUG_DRAG) {
15398            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15399                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15400        }
15401        Surface surface = new Surface();
15402        try {
15403            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15404                    flags, shadowSize.x, shadowSize.y, surface);
15405            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15406                    + " surface=" + surface);
15407            if (token != null) {
15408                Canvas canvas = surface.lockCanvas(null);
15409                try {
15410                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15411                    shadowBuilder.onDrawShadow(canvas);
15412                } finally {
15413                    surface.unlockCanvasAndPost(canvas);
15414                }
15415
15416                final ViewRootImpl root = getViewRootImpl();
15417
15418                // Cache the local state object for delivery with DragEvents
15419                root.setLocalDragState(myLocalState);
15420
15421                // repurpose 'shadowSize' for the last touch point
15422                root.getLastTouchPoint(shadowSize);
15423
15424                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15425                        shadowSize.x, shadowSize.y,
15426                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15427                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15428
15429                // Off and running!  Release our local surface instance; the drag
15430                // shadow surface is now managed by the system process.
15431                surface.release();
15432            }
15433        } catch (Exception e) {
15434            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15435            surface.destroy();
15436        }
15437
15438        return okay;
15439    }
15440
15441    /**
15442     * Handles drag events sent by the system following a call to
15443     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15444     *<p>
15445     * When the system calls this method, it passes a
15446     * {@link android.view.DragEvent} object. A call to
15447     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15448     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15449     * operation.
15450     * @param event The {@link android.view.DragEvent} sent by the system.
15451     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15452     * in DragEvent, indicating the type of drag event represented by this object.
15453     * @return {@code true} if the method was successful, otherwise {@code false}.
15454     * <p>
15455     *  The method should return {@code true} in response to an action type of
15456     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15457     *  operation.
15458     * </p>
15459     * <p>
15460     *  The method should also return {@code true} in response to an action type of
15461     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15462     *  {@code false} if it didn't.
15463     * </p>
15464     */
15465    public boolean onDragEvent(DragEvent event) {
15466        return false;
15467    }
15468
15469    /**
15470     * Detects if this View is enabled and has a drag event listener.
15471     * If both are true, then it calls the drag event listener with the
15472     * {@link android.view.DragEvent} it received. If the drag event listener returns
15473     * {@code true}, then dispatchDragEvent() returns {@code true}.
15474     * <p>
15475     * For all other cases, the method calls the
15476     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15477     * method and returns its result.
15478     * </p>
15479     * <p>
15480     * This ensures that a drag event is always consumed, even if the View does not have a drag
15481     * event listener. However, if the View has a listener and the listener returns true, then
15482     * onDragEvent() is not called.
15483     * </p>
15484     */
15485    public boolean dispatchDragEvent(DragEvent event) {
15486        //noinspection SimplifiableIfStatement
15487        ListenerInfo li = mListenerInfo;
15488        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15489                && li.mOnDragListener.onDrag(this, event)) {
15490            return true;
15491        }
15492        return onDragEvent(event);
15493    }
15494
15495    boolean canAcceptDrag() {
15496        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15497    }
15498
15499    /**
15500     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15501     * it is ever exposed at all.
15502     * @hide
15503     */
15504    public void onCloseSystemDialogs(String reason) {
15505    }
15506
15507    /**
15508     * Given a Drawable whose bounds have been set to draw into this view,
15509     * update a Region being computed for
15510     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15511     * that any non-transparent parts of the Drawable are removed from the
15512     * given transparent region.
15513     *
15514     * @param dr The Drawable whose transparency is to be applied to the region.
15515     * @param region A Region holding the current transparency information,
15516     * where any parts of the region that are set are considered to be
15517     * transparent.  On return, this region will be modified to have the
15518     * transparency information reduced by the corresponding parts of the
15519     * Drawable that are not transparent.
15520     * {@hide}
15521     */
15522    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15523        if (DBG) {
15524            Log.i("View", "Getting transparent region for: " + this);
15525        }
15526        final Region r = dr.getTransparentRegion();
15527        final Rect db = dr.getBounds();
15528        final AttachInfo attachInfo = mAttachInfo;
15529        if (r != null && attachInfo != null) {
15530            final int w = getRight()-getLeft();
15531            final int h = getBottom()-getTop();
15532            if (db.left > 0) {
15533                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15534                r.op(0, 0, db.left, h, Region.Op.UNION);
15535            }
15536            if (db.right < w) {
15537                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15538                r.op(db.right, 0, w, h, Region.Op.UNION);
15539            }
15540            if (db.top > 0) {
15541                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15542                r.op(0, 0, w, db.top, Region.Op.UNION);
15543            }
15544            if (db.bottom < h) {
15545                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15546                r.op(0, db.bottom, w, h, Region.Op.UNION);
15547            }
15548            final int[] location = attachInfo.mTransparentLocation;
15549            getLocationInWindow(location);
15550            r.translate(location[0], location[1]);
15551            region.op(r, Region.Op.INTERSECT);
15552        } else {
15553            region.op(db, Region.Op.DIFFERENCE);
15554        }
15555    }
15556
15557    private void checkForLongClick(int delayOffset) {
15558        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15559            mHasPerformedLongPress = false;
15560
15561            if (mPendingCheckForLongPress == null) {
15562                mPendingCheckForLongPress = new CheckForLongPress();
15563            }
15564            mPendingCheckForLongPress.rememberWindowAttachCount();
15565            postDelayed(mPendingCheckForLongPress,
15566                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15567        }
15568    }
15569
15570    /**
15571     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15572     * LayoutInflater} class, which provides a full range of options for view inflation.
15573     *
15574     * @param context The Context object for your activity or application.
15575     * @param resource The resource ID to inflate
15576     * @param root A view group that will be the parent.  Used to properly inflate the
15577     * layout_* parameters.
15578     * @see LayoutInflater
15579     */
15580    public static View inflate(Context context, int resource, ViewGroup root) {
15581        LayoutInflater factory = LayoutInflater.from(context);
15582        return factory.inflate(resource, root);
15583    }
15584
15585    /**
15586     * Scroll the view with standard behavior for scrolling beyond the normal
15587     * content boundaries. Views that call this method should override
15588     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15589     * results of an over-scroll operation.
15590     *
15591     * Views can use this method to handle any touch or fling-based scrolling.
15592     *
15593     * @param deltaX Change in X in pixels
15594     * @param deltaY Change in Y in pixels
15595     * @param scrollX Current X scroll value in pixels before applying deltaX
15596     * @param scrollY Current Y scroll value in pixels before applying deltaY
15597     * @param scrollRangeX Maximum content scroll range along the X axis
15598     * @param scrollRangeY Maximum content scroll range along the Y axis
15599     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15600     *          along the X axis.
15601     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15602     *          along the Y axis.
15603     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15604     * @return true if scrolling was clamped to an over-scroll boundary along either
15605     *          axis, false otherwise.
15606     */
15607    @SuppressWarnings({"UnusedParameters"})
15608    protected boolean overScrollBy(int deltaX, int deltaY,
15609            int scrollX, int scrollY,
15610            int scrollRangeX, int scrollRangeY,
15611            int maxOverScrollX, int maxOverScrollY,
15612            boolean isTouchEvent) {
15613        final int overScrollMode = mOverScrollMode;
15614        final boolean canScrollHorizontal =
15615                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15616        final boolean canScrollVertical =
15617                computeVerticalScrollRange() > computeVerticalScrollExtent();
15618        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15619                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15620        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15621                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15622
15623        int newScrollX = scrollX + deltaX;
15624        if (!overScrollHorizontal) {
15625            maxOverScrollX = 0;
15626        }
15627
15628        int newScrollY = scrollY + deltaY;
15629        if (!overScrollVertical) {
15630            maxOverScrollY = 0;
15631        }
15632
15633        // Clamp values if at the limits and record
15634        final int left = -maxOverScrollX;
15635        final int right = maxOverScrollX + scrollRangeX;
15636        final int top = -maxOverScrollY;
15637        final int bottom = maxOverScrollY + scrollRangeY;
15638
15639        boolean clampedX = false;
15640        if (newScrollX > right) {
15641            newScrollX = right;
15642            clampedX = true;
15643        } else if (newScrollX < left) {
15644            newScrollX = left;
15645            clampedX = true;
15646        }
15647
15648        boolean clampedY = false;
15649        if (newScrollY > bottom) {
15650            newScrollY = bottom;
15651            clampedY = true;
15652        } else if (newScrollY < top) {
15653            newScrollY = top;
15654            clampedY = true;
15655        }
15656
15657        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15658
15659        return clampedX || clampedY;
15660    }
15661
15662    /**
15663     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15664     * respond to the results of an over-scroll operation.
15665     *
15666     * @param scrollX New X scroll value in pixels
15667     * @param scrollY New Y scroll value in pixels
15668     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15669     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15670     */
15671    protected void onOverScrolled(int scrollX, int scrollY,
15672            boolean clampedX, boolean clampedY) {
15673        // Intentionally empty.
15674    }
15675
15676    /**
15677     * Returns the over-scroll mode for this view. The result will be
15678     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15679     * (allow over-scrolling only if the view content is larger than the container),
15680     * or {@link #OVER_SCROLL_NEVER}.
15681     *
15682     * @return This view's over-scroll mode.
15683     */
15684    public int getOverScrollMode() {
15685        return mOverScrollMode;
15686    }
15687
15688    /**
15689     * Set the over-scroll mode for this view. Valid over-scroll modes are
15690     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
15691     * (allow over-scrolling only if the view content is larger than the container),
15692     * or {@link #OVER_SCROLL_NEVER}.
15693     *
15694     * Setting the over-scroll mode of a view will have an effect only if the
15695     * view is capable of scrolling.
15696     *
15697     * @param overScrollMode The new over-scroll mode for this view.
15698     */
15699    public void setOverScrollMode(int overScrollMode) {
15700        if (overScrollMode != OVER_SCROLL_ALWAYS &&
15701                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
15702                overScrollMode != OVER_SCROLL_NEVER) {
15703            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
15704        }
15705        mOverScrollMode = overScrollMode;
15706    }
15707
15708    /**
15709     * Gets a scale factor that determines the distance the view should scroll
15710     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
15711     * @return The vertical scroll scale factor.
15712     * @hide
15713     */
15714    protected float getVerticalScrollFactor() {
15715        if (mVerticalScrollFactor == 0) {
15716            TypedValue outValue = new TypedValue();
15717            if (!mContext.getTheme().resolveAttribute(
15718                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
15719                throw new IllegalStateException(
15720                        "Expected theme to define listPreferredItemHeight.");
15721            }
15722            mVerticalScrollFactor = outValue.getDimension(
15723                    mContext.getResources().getDisplayMetrics());
15724        }
15725        return mVerticalScrollFactor;
15726    }
15727
15728    /**
15729     * Gets a scale factor that determines the distance the view should scroll
15730     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
15731     * @return The horizontal scroll scale factor.
15732     * @hide
15733     */
15734    protected float getHorizontalScrollFactor() {
15735        // TODO: Should use something else.
15736        return getVerticalScrollFactor();
15737    }
15738
15739    /**
15740     * Return the value specifying the text direction or policy that was set with
15741     * {@link #setTextDirection(int)}.
15742     *
15743     * @return the defined text direction. It can be one of:
15744     *
15745     * {@link #TEXT_DIRECTION_INHERIT},
15746     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15747     * {@link #TEXT_DIRECTION_ANY_RTL},
15748     * {@link #TEXT_DIRECTION_LTR},
15749     * {@link #TEXT_DIRECTION_RTL},
15750     * {@link #TEXT_DIRECTION_LOCALE}
15751     */
15752    @ViewDebug.ExportedProperty(category = "text", mapping = {
15753            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
15754            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
15755            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
15756            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
15757            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
15758            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
15759    })
15760    public int getTextDirection() {
15761        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
15762    }
15763
15764    /**
15765     * Set the text direction.
15766     *
15767     * @param textDirection the direction to set. Should be one of:
15768     *
15769     * {@link #TEXT_DIRECTION_INHERIT},
15770     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15771     * {@link #TEXT_DIRECTION_ANY_RTL},
15772     * {@link #TEXT_DIRECTION_LTR},
15773     * {@link #TEXT_DIRECTION_RTL},
15774     * {@link #TEXT_DIRECTION_LOCALE}
15775     */
15776    public void setTextDirection(int textDirection) {
15777        if (getTextDirection() != textDirection) {
15778            // Reset the current text direction and the resolved one
15779            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
15780            resetResolvedTextDirection();
15781            // Set the new text direction
15782            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
15783            // Refresh
15784            requestLayout();
15785            invalidate(true);
15786        }
15787    }
15788
15789    /**
15790     * Return the resolved text direction.
15791     *
15792     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
15793     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
15794     * up the parent chain of the view. if there is no parent, then it will return the default
15795     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
15796     *
15797     * @return the resolved text direction. Returns one of:
15798     *
15799     * {@link #TEXT_DIRECTION_FIRST_STRONG}
15800     * {@link #TEXT_DIRECTION_ANY_RTL},
15801     * {@link #TEXT_DIRECTION_LTR},
15802     * {@link #TEXT_DIRECTION_RTL},
15803     * {@link #TEXT_DIRECTION_LOCALE}
15804     */
15805    public int getResolvedTextDirection() {
15806        // The text direction will be resolved only if needed
15807        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
15808            resolveTextDirection();
15809        }
15810        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
15811    }
15812
15813    /**
15814     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
15815     * resolution is done.
15816     */
15817    public void resolveTextDirection() {
15818        // Reset any previous text direction resolution
15819        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15820
15821        if (hasRtlSupport()) {
15822            // Set resolved text direction flag depending on text direction flag
15823            final int textDirection = getTextDirection();
15824            switch(textDirection) {
15825                case TEXT_DIRECTION_INHERIT:
15826                    if (canResolveTextDirection()) {
15827                        ViewGroup viewGroup = ((ViewGroup) mParent);
15828
15829                        // Set current resolved direction to the same value as the parent's one
15830                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
15831                        switch (parentResolvedDirection) {
15832                            case TEXT_DIRECTION_FIRST_STRONG:
15833                            case TEXT_DIRECTION_ANY_RTL:
15834                            case TEXT_DIRECTION_LTR:
15835                            case TEXT_DIRECTION_RTL:
15836                            case TEXT_DIRECTION_LOCALE:
15837                                mPrivateFlags2 |=
15838                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15839                                break;
15840                            default:
15841                                // Default resolved direction is "first strong" heuristic
15842                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15843                        }
15844                    } else {
15845                        // We cannot do the resolution if there is no parent, so use the default one
15846                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15847                    }
15848                    break;
15849                case TEXT_DIRECTION_FIRST_STRONG:
15850                case TEXT_DIRECTION_ANY_RTL:
15851                case TEXT_DIRECTION_LTR:
15852                case TEXT_DIRECTION_RTL:
15853                case TEXT_DIRECTION_LOCALE:
15854                    // Resolved direction is the same as text direction
15855                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
15856                    break;
15857                default:
15858                    // Default resolved direction is "first strong" heuristic
15859                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15860            }
15861        } else {
15862            // Default resolved direction is "first strong" heuristic
15863            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
15864        }
15865
15866        // Set to resolved
15867        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
15868        onResolvedTextDirectionChanged();
15869    }
15870
15871    /**
15872     * Called when text direction has been resolved. Subclasses that care about text direction
15873     * resolution should override this method.
15874     *
15875     * The default implementation does nothing.
15876     */
15877    public void onResolvedTextDirectionChanged() {
15878    }
15879
15880    /**
15881     * Check if text direction resolution can be done.
15882     *
15883     * @return true if text direction resolution can be done otherwise return false.
15884     */
15885    public boolean canResolveTextDirection() {
15886        switch (getTextDirection()) {
15887            case TEXT_DIRECTION_INHERIT:
15888                return (mParent != null) && (mParent instanceof ViewGroup);
15889            default:
15890                return true;
15891        }
15892    }
15893
15894    /**
15895     * Reset resolved text direction. Text direction can be resolved with a call to
15896     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
15897     * reset is done.
15898     */
15899    public void resetResolvedTextDirection() {
15900        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
15901        onResolvedTextDirectionReset();
15902    }
15903
15904    /**
15905     * Called when text direction is reset. Subclasses that care about text direction reset should
15906     * override this method and do a reset of the text direction of their children. The default
15907     * implementation does nothing.
15908     */
15909    public void onResolvedTextDirectionReset() {
15910    }
15911
15912    /**
15913     * Return the value specifying the text alignment or policy that was set with
15914     * {@link #setTextAlignment(int)}.
15915     *
15916     * @return the defined text alignment. It can be one of:
15917     *
15918     * {@link #TEXT_ALIGNMENT_INHERIT},
15919     * {@link #TEXT_ALIGNMENT_GRAVITY},
15920     * {@link #TEXT_ALIGNMENT_CENTER},
15921     * {@link #TEXT_ALIGNMENT_TEXT_START},
15922     * {@link #TEXT_ALIGNMENT_TEXT_END},
15923     * {@link #TEXT_ALIGNMENT_VIEW_START},
15924     * {@link #TEXT_ALIGNMENT_VIEW_END}
15925     */
15926    @ViewDebug.ExportedProperty(category = "text", mapping = {
15927            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15928            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15929            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15930            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15931            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15932            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15933            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15934    })
15935    public int getTextAlignment() {
15936        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
15937    }
15938
15939    /**
15940     * Set the text alignment.
15941     *
15942     * @param textAlignment The text alignment to set. Should be one of
15943     *
15944     * {@link #TEXT_ALIGNMENT_INHERIT},
15945     * {@link #TEXT_ALIGNMENT_GRAVITY},
15946     * {@link #TEXT_ALIGNMENT_CENTER},
15947     * {@link #TEXT_ALIGNMENT_TEXT_START},
15948     * {@link #TEXT_ALIGNMENT_TEXT_END},
15949     * {@link #TEXT_ALIGNMENT_VIEW_START},
15950     * {@link #TEXT_ALIGNMENT_VIEW_END}
15951     *
15952     * @attr ref android.R.styleable#View_textAlignment
15953     */
15954    public void setTextAlignment(int textAlignment) {
15955        if (textAlignment != getTextAlignment()) {
15956            // Reset the current and resolved text alignment
15957            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
15958            resetResolvedTextAlignment();
15959            // Set the new text alignment
15960            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
15961            // Refresh
15962            requestLayout();
15963            invalidate(true);
15964        }
15965    }
15966
15967    /**
15968     * Return the resolved text alignment.
15969     *
15970     * The resolved text alignment. This needs resolution if the value is
15971     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
15972     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
15973     *
15974     * @return the resolved text alignment. Returns one of:
15975     *
15976     * {@link #TEXT_ALIGNMENT_GRAVITY},
15977     * {@link #TEXT_ALIGNMENT_CENTER},
15978     * {@link #TEXT_ALIGNMENT_TEXT_START},
15979     * {@link #TEXT_ALIGNMENT_TEXT_END},
15980     * {@link #TEXT_ALIGNMENT_VIEW_START},
15981     * {@link #TEXT_ALIGNMENT_VIEW_END}
15982     */
15983    @ViewDebug.ExportedProperty(category = "text", mapping = {
15984            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
15985            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
15986            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
15987            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
15988            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
15989            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
15990            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
15991    })
15992    public int getResolvedTextAlignment() {
15993        // If text alignment is not resolved, then resolve it
15994        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
15995            resolveTextAlignment();
15996        }
15997        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
15998    }
15999
16000    /**
16001     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16002     * resolution is done.
16003     */
16004    public void resolveTextAlignment() {
16005        // Reset any previous text alignment resolution
16006        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16007
16008        if (hasRtlSupport()) {
16009            // Set resolved text alignment flag depending on text alignment flag
16010            final int textAlignment = getTextAlignment();
16011            switch (textAlignment) {
16012                case TEXT_ALIGNMENT_INHERIT:
16013                    // Check if we can resolve the text alignment
16014                    if (canResolveLayoutDirection() && mParent instanceof View) {
16015                        View view = (View) mParent;
16016
16017                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16018                        switch (parentResolvedTextAlignment) {
16019                            case TEXT_ALIGNMENT_GRAVITY:
16020                            case TEXT_ALIGNMENT_TEXT_START:
16021                            case TEXT_ALIGNMENT_TEXT_END:
16022                            case TEXT_ALIGNMENT_CENTER:
16023                            case TEXT_ALIGNMENT_VIEW_START:
16024                            case TEXT_ALIGNMENT_VIEW_END:
16025                                // Resolved text alignment is the same as the parent resolved
16026                                // text alignment
16027                                mPrivateFlags2 |=
16028                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16029                                break;
16030                            default:
16031                                // Use default resolved text alignment
16032                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16033                        }
16034                    }
16035                    else {
16036                        // We cannot do the resolution if there is no parent so use the default
16037                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16038                    }
16039                    break;
16040                case TEXT_ALIGNMENT_GRAVITY:
16041                case TEXT_ALIGNMENT_TEXT_START:
16042                case TEXT_ALIGNMENT_TEXT_END:
16043                case TEXT_ALIGNMENT_CENTER:
16044                case TEXT_ALIGNMENT_VIEW_START:
16045                case TEXT_ALIGNMENT_VIEW_END:
16046                    // Resolved text alignment is the same as text alignment
16047                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16048                    break;
16049                default:
16050                    // Use default resolved text alignment
16051                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16052            }
16053        } else {
16054            // Use default resolved text alignment
16055            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16056        }
16057
16058        // Set the resolved
16059        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16060        onResolvedTextAlignmentChanged();
16061    }
16062
16063    /**
16064     * Check if text alignment resolution can be done.
16065     *
16066     * @return true if text alignment resolution can be done otherwise return false.
16067     */
16068    public boolean canResolveTextAlignment() {
16069        switch (getTextAlignment()) {
16070            case TEXT_DIRECTION_INHERIT:
16071                return (mParent != null);
16072            default:
16073                return true;
16074        }
16075    }
16076
16077    /**
16078     * Called when text alignment has been resolved. Subclasses that care about text alignment
16079     * resolution should override this method.
16080     *
16081     * The default implementation does nothing.
16082     */
16083    public void onResolvedTextAlignmentChanged() {
16084    }
16085
16086    /**
16087     * Reset resolved text alignment. Text alignment can be resolved with a call to
16088     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16089     * reset is done.
16090     */
16091    public void resetResolvedTextAlignment() {
16092        // Reset any previous text alignment resolution
16093        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16094        onResolvedTextAlignmentReset();
16095    }
16096
16097    /**
16098     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16099     * override this method and do a reset of the text alignment of their children. The default
16100     * implementation does nothing.
16101     */
16102    public void onResolvedTextAlignmentReset() {
16103    }
16104
16105    //
16106    // Properties
16107    //
16108    /**
16109     * A Property wrapper around the <code>alpha</code> functionality handled by the
16110     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16111     */
16112    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16113        @Override
16114        public void setValue(View object, float value) {
16115            object.setAlpha(value);
16116        }
16117
16118        @Override
16119        public Float get(View object) {
16120            return object.getAlpha();
16121        }
16122    };
16123
16124    /**
16125     * A Property wrapper around the <code>translationX</code> functionality handled by the
16126     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16127     */
16128    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16129        @Override
16130        public void setValue(View object, float value) {
16131            object.setTranslationX(value);
16132        }
16133
16134                @Override
16135        public Float get(View object) {
16136            return object.getTranslationX();
16137        }
16138    };
16139
16140    /**
16141     * A Property wrapper around the <code>translationY</code> functionality handled by the
16142     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16143     */
16144    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16145        @Override
16146        public void setValue(View object, float value) {
16147            object.setTranslationY(value);
16148        }
16149
16150        @Override
16151        public Float get(View object) {
16152            return object.getTranslationY();
16153        }
16154    };
16155
16156    /**
16157     * A Property wrapper around the <code>x</code> functionality handled by the
16158     * {@link View#setX(float)} and {@link View#getX()} methods.
16159     */
16160    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16161        @Override
16162        public void setValue(View object, float value) {
16163            object.setX(value);
16164        }
16165
16166        @Override
16167        public Float get(View object) {
16168            return object.getX();
16169        }
16170    };
16171
16172    /**
16173     * A Property wrapper around the <code>y</code> functionality handled by the
16174     * {@link View#setY(float)} and {@link View#getY()} methods.
16175     */
16176    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16177        @Override
16178        public void setValue(View object, float value) {
16179            object.setY(value);
16180        }
16181
16182        @Override
16183        public Float get(View object) {
16184            return object.getY();
16185        }
16186    };
16187
16188    /**
16189     * A Property wrapper around the <code>rotation</code> functionality handled by the
16190     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16191     */
16192    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16193        @Override
16194        public void setValue(View object, float value) {
16195            object.setRotation(value);
16196        }
16197
16198        @Override
16199        public Float get(View object) {
16200            return object.getRotation();
16201        }
16202    };
16203
16204    /**
16205     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16206     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16207     */
16208    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16209        @Override
16210        public void setValue(View object, float value) {
16211            object.setRotationX(value);
16212        }
16213
16214        @Override
16215        public Float get(View object) {
16216            return object.getRotationX();
16217        }
16218    };
16219
16220    /**
16221     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16222     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16223     */
16224    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16225        @Override
16226        public void setValue(View object, float value) {
16227            object.setRotationY(value);
16228        }
16229
16230        @Override
16231        public Float get(View object) {
16232            return object.getRotationY();
16233        }
16234    };
16235
16236    /**
16237     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16238     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16239     */
16240    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16241        @Override
16242        public void setValue(View object, float value) {
16243            object.setScaleX(value);
16244        }
16245
16246        @Override
16247        public Float get(View object) {
16248            return object.getScaleX();
16249        }
16250    };
16251
16252    /**
16253     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16254     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16255     */
16256    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16257        @Override
16258        public void setValue(View object, float value) {
16259            object.setScaleY(value);
16260        }
16261
16262        @Override
16263        public Float get(View object) {
16264            return object.getScaleY();
16265        }
16266    };
16267
16268    /**
16269     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16270     * Each MeasureSpec represents a requirement for either the width or the height.
16271     * A MeasureSpec is comprised of a size and a mode. There are three possible
16272     * modes:
16273     * <dl>
16274     * <dt>UNSPECIFIED</dt>
16275     * <dd>
16276     * The parent has not imposed any constraint on the child. It can be whatever size
16277     * it wants.
16278     * </dd>
16279     *
16280     * <dt>EXACTLY</dt>
16281     * <dd>
16282     * The parent has determined an exact size for the child. The child is going to be
16283     * given those bounds regardless of how big it wants to be.
16284     * </dd>
16285     *
16286     * <dt>AT_MOST</dt>
16287     * <dd>
16288     * The child can be as large as it wants up to the specified size.
16289     * </dd>
16290     * </dl>
16291     *
16292     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16293     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16294     */
16295    public static class MeasureSpec {
16296        private static final int MODE_SHIFT = 30;
16297        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16298
16299        /**
16300         * Measure specification mode: The parent has not imposed any constraint
16301         * on the child. It can be whatever size it wants.
16302         */
16303        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16304
16305        /**
16306         * Measure specification mode: The parent has determined an exact size
16307         * for the child. The child is going to be given those bounds regardless
16308         * of how big it wants to be.
16309         */
16310        public static final int EXACTLY     = 1 << MODE_SHIFT;
16311
16312        /**
16313         * Measure specification mode: The child can be as large as it wants up
16314         * to the specified size.
16315         */
16316        public static final int AT_MOST     = 2 << MODE_SHIFT;
16317
16318        /**
16319         * Creates a measure specification based on the supplied size and mode.
16320         *
16321         * The mode must always be one of the following:
16322         * <ul>
16323         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16324         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16325         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16326         * </ul>
16327         *
16328         * @param size the size of the measure specification
16329         * @param mode the mode of the measure specification
16330         * @return the measure specification based on size and mode
16331         */
16332        public static int makeMeasureSpec(int size, int mode) {
16333            return size + mode;
16334        }
16335
16336        /**
16337         * Extracts the mode from the supplied measure specification.
16338         *
16339         * @param measureSpec the measure specification to extract the mode from
16340         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16341         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16342         *         {@link android.view.View.MeasureSpec#EXACTLY}
16343         */
16344        public static int getMode(int measureSpec) {
16345            return (measureSpec & MODE_MASK);
16346        }
16347
16348        /**
16349         * Extracts the size from the supplied measure specification.
16350         *
16351         * @param measureSpec the measure specification to extract the size from
16352         * @return the size in pixels defined in the supplied measure specification
16353         */
16354        public static int getSize(int measureSpec) {
16355            return (measureSpec & ~MODE_MASK);
16356        }
16357
16358        /**
16359         * Returns a String representation of the specified measure
16360         * specification.
16361         *
16362         * @param measureSpec the measure specification to convert to a String
16363         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16364         */
16365        public static String toString(int measureSpec) {
16366            int mode = getMode(measureSpec);
16367            int size = getSize(measureSpec);
16368
16369            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16370
16371            if (mode == UNSPECIFIED)
16372                sb.append("UNSPECIFIED ");
16373            else if (mode == EXACTLY)
16374                sb.append("EXACTLY ");
16375            else if (mode == AT_MOST)
16376                sb.append("AT_MOST ");
16377            else
16378                sb.append(mode).append(" ");
16379
16380            sb.append(size);
16381            return sb.toString();
16382        }
16383    }
16384
16385    class CheckForLongPress implements Runnable {
16386
16387        private int mOriginalWindowAttachCount;
16388
16389        public void run() {
16390            if (isPressed() && (mParent != null)
16391                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16392                if (performLongClick()) {
16393                    mHasPerformedLongPress = true;
16394                }
16395            }
16396        }
16397
16398        public void rememberWindowAttachCount() {
16399            mOriginalWindowAttachCount = mWindowAttachCount;
16400        }
16401    }
16402
16403    private final class CheckForTap implements Runnable {
16404        public void run() {
16405            mPrivateFlags &= ~PREPRESSED;
16406            setPressed(true);
16407            checkForLongClick(ViewConfiguration.getTapTimeout());
16408        }
16409    }
16410
16411    private final class PerformClick implements Runnable {
16412        public void run() {
16413            performClick();
16414        }
16415    }
16416
16417    /** @hide */
16418    public void hackTurnOffWindowResizeAnim(boolean off) {
16419        mAttachInfo.mTurnOffWindowResizeAnim = off;
16420    }
16421
16422    /**
16423     * This method returns a ViewPropertyAnimator object, which can be used to animate
16424     * specific properties on this View.
16425     *
16426     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16427     */
16428    public ViewPropertyAnimator animate() {
16429        if (mAnimator == null) {
16430            mAnimator = new ViewPropertyAnimator(this);
16431        }
16432        return mAnimator;
16433    }
16434
16435    /**
16436     * Interface definition for a callback to be invoked when a key event is
16437     * dispatched to this view. The callback will be invoked before the key
16438     * event is given to the view.
16439     */
16440    public interface OnKeyListener {
16441        /**
16442         * Called when a key is dispatched to a view. This allows listeners to
16443         * get a chance to respond before the target view.
16444         *
16445         * @param v The view the key has been dispatched to.
16446         * @param keyCode The code for the physical key that was pressed
16447         * @param event The KeyEvent object containing full information about
16448         *        the event.
16449         * @return True if the listener has consumed the event, false otherwise.
16450         */
16451        boolean onKey(View v, int keyCode, KeyEvent event);
16452    }
16453
16454    /**
16455     * Interface definition for a callback to be invoked when a touch event is
16456     * dispatched to this view. The callback will be invoked before the touch
16457     * event is given to the view.
16458     */
16459    public interface OnTouchListener {
16460        /**
16461         * Called when a touch event is dispatched to a view. This allows listeners to
16462         * get a chance to respond before the target view.
16463         *
16464         * @param v The view the touch event has been dispatched to.
16465         * @param event The MotionEvent object containing full information about
16466         *        the event.
16467         * @return True if the listener has consumed the event, false otherwise.
16468         */
16469        boolean onTouch(View v, MotionEvent event);
16470    }
16471
16472    /**
16473     * Interface definition for a callback to be invoked when a hover event is
16474     * dispatched to this view. The callback will be invoked before the hover
16475     * event is given to the view.
16476     */
16477    public interface OnHoverListener {
16478        /**
16479         * Called when a hover event is dispatched to a view. This allows listeners to
16480         * get a chance to respond before the target view.
16481         *
16482         * @param v The view the hover event has been dispatched to.
16483         * @param event The MotionEvent object containing full information about
16484         *        the event.
16485         * @return True if the listener has consumed the event, false otherwise.
16486         */
16487        boolean onHover(View v, MotionEvent event);
16488    }
16489
16490    /**
16491     * Interface definition for a callback to be invoked when a generic motion event is
16492     * dispatched to this view. The callback will be invoked before the generic motion
16493     * event is given to the view.
16494     */
16495    public interface OnGenericMotionListener {
16496        /**
16497         * Called when a generic motion event is dispatched to a view. This allows listeners to
16498         * get a chance to respond before the target view.
16499         *
16500         * @param v The view the generic motion event has been dispatched to.
16501         * @param event The MotionEvent object containing full information about
16502         *        the event.
16503         * @return True if the listener has consumed the event, false otherwise.
16504         */
16505        boolean onGenericMotion(View v, MotionEvent event);
16506    }
16507
16508    /**
16509     * Interface definition for a callback to be invoked when a view has been clicked and held.
16510     */
16511    public interface OnLongClickListener {
16512        /**
16513         * Called when a view has been clicked and held.
16514         *
16515         * @param v The view that was clicked and held.
16516         *
16517         * @return true if the callback consumed the long click, false otherwise.
16518         */
16519        boolean onLongClick(View v);
16520    }
16521
16522    /**
16523     * Interface definition for a callback to be invoked when a drag is being dispatched
16524     * to this view.  The callback will be invoked before the hosting view's own
16525     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16526     * onDrag(event) behavior, it should return 'false' from this callback.
16527     *
16528     * <div class="special reference">
16529     * <h3>Developer Guides</h3>
16530     * <p>For a guide to implementing drag and drop features, read the
16531     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16532     * </div>
16533     */
16534    public interface OnDragListener {
16535        /**
16536         * Called when a drag event is dispatched to a view. This allows listeners
16537         * to get a chance to override base View behavior.
16538         *
16539         * @param v The View that received the drag event.
16540         * @param event The {@link android.view.DragEvent} object for the drag event.
16541         * @return {@code true} if the drag event was handled successfully, or {@code false}
16542         * if the drag event was not handled. Note that {@code false} will trigger the View
16543         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16544         */
16545        boolean onDrag(View v, DragEvent event);
16546    }
16547
16548    /**
16549     * Interface definition for a callback to be invoked when the focus state of
16550     * a view changed.
16551     */
16552    public interface OnFocusChangeListener {
16553        /**
16554         * Called when the focus state of a view has changed.
16555         *
16556         * @param v The view whose state has changed.
16557         * @param hasFocus The new focus state of v.
16558         */
16559        void onFocusChange(View v, boolean hasFocus);
16560    }
16561
16562    /**
16563     * Interface definition for a callback to be invoked when a view is clicked.
16564     */
16565    public interface OnClickListener {
16566        /**
16567         * Called when a view has been clicked.
16568         *
16569         * @param v The view that was clicked.
16570         */
16571        void onClick(View v);
16572    }
16573
16574    /**
16575     * Interface definition for a callback to be invoked when the context menu
16576     * for this view is being built.
16577     */
16578    public interface OnCreateContextMenuListener {
16579        /**
16580         * Called when the context menu for this view is being built. It is not
16581         * safe to hold onto the menu after this method returns.
16582         *
16583         * @param menu The context menu that is being built
16584         * @param v The view for which the context menu is being built
16585         * @param menuInfo Extra information about the item for which the
16586         *            context menu should be shown. This information will vary
16587         *            depending on the class of v.
16588         */
16589        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16590    }
16591
16592    /**
16593     * Interface definition for a callback to be invoked when the status bar changes
16594     * visibility.  This reports <strong>global</strong> changes to the system UI
16595     * state, not just what the application is requesting.
16596     *
16597     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16598     */
16599    public interface OnSystemUiVisibilityChangeListener {
16600        /**
16601         * Called when the status bar changes visibility because of a call to
16602         * {@link View#setSystemUiVisibility(int)}.
16603         *
16604         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
16605         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
16606         * <strong>global</strong> state of the UI visibility flags, not what your
16607         * app is currently applying.
16608         */
16609        public void onSystemUiVisibilityChange(int visibility);
16610    }
16611
16612    /**
16613     * Interface definition for a callback to be invoked when this view is attached
16614     * or detached from its window.
16615     */
16616    public interface OnAttachStateChangeListener {
16617        /**
16618         * Called when the view is attached to a window.
16619         * @param v The view that was attached
16620         */
16621        public void onViewAttachedToWindow(View v);
16622        /**
16623         * Called when the view is detached from a window.
16624         * @param v The view that was detached
16625         */
16626        public void onViewDetachedFromWindow(View v);
16627    }
16628
16629    private final class UnsetPressedState implements Runnable {
16630        public void run() {
16631            setPressed(false);
16632        }
16633    }
16634
16635    /**
16636     * Base class for derived classes that want to save and restore their own
16637     * state in {@link android.view.View#onSaveInstanceState()}.
16638     */
16639    public static class BaseSavedState extends AbsSavedState {
16640        /**
16641         * Constructor used when reading from a parcel. Reads the state of the superclass.
16642         *
16643         * @param source
16644         */
16645        public BaseSavedState(Parcel source) {
16646            super(source);
16647        }
16648
16649        /**
16650         * Constructor called by derived classes when creating their SavedState objects
16651         *
16652         * @param superState The state of the superclass of this view
16653         */
16654        public BaseSavedState(Parcelable superState) {
16655            super(superState);
16656        }
16657
16658        public static final Parcelable.Creator<BaseSavedState> CREATOR =
16659                new Parcelable.Creator<BaseSavedState>() {
16660            public BaseSavedState createFromParcel(Parcel in) {
16661                return new BaseSavedState(in);
16662            }
16663
16664            public BaseSavedState[] newArray(int size) {
16665                return new BaseSavedState[size];
16666            }
16667        };
16668    }
16669
16670    /**
16671     * A set of information given to a view when it is attached to its parent
16672     * window.
16673     */
16674    static class AttachInfo {
16675        interface Callbacks {
16676            void playSoundEffect(int effectId);
16677            boolean performHapticFeedback(int effectId, boolean always);
16678        }
16679
16680        /**
16681         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
16682         * to a Handler. This class contains the target (View) to invalidate and
16683         * the coordinates of the dirty rectangle.
16684         *
16685         * For performance purposes, this class also implements a pool of up to
16686         * POOL_LIMIT objects that get reused. This reduces memory allocations
16687         * whenever possible.
16688         */
16689        static class InvalidateInfo implements Poolable<InvalidateInfo> {
16690            private static final int POOL_LIMIT = 10;
16691            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
16692                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
16693                        public InvalidateInfo newInstance() {
16694                            return new InvalidateInfo();
16695                        }
16696
16697                        public void onAcquired(InvalidateInfo element) {
16698                        }
16699
16700                        public void onReleased(InvalidateInfo element) {
16701                            element.target = null;
16702                        }
16703                    }, POOL_LIMIT)
16704            );
16705
16706            private InvalidateInfo mNext;
16707            private boolean mIsPooled;
16708
16709            View target;
16710
16711            int left;
16712            int top;
16713            int right;
16714            int bottom;
16715
16716            public void setNextPoolable(InvalidateInfo element) {
16717                mNext = element;
16718            }
16719
16720            public InvalidateInfo getNextPoolable() {
16721                return mNext;
16722            }
16723
16724            static InvalidateInfo acquire() {
16725                return sPool.acquire();
16726            }
16727
16728            void release() {
16729                sPool.release(this);
16730            }
16731
16732            public boolean isPooled() {
16733                return mIsPooled;
16734            }
16735
16736            public void setPooled(boolean isPooled) {
16737                mIsPooled = isPooled;
16738            }
16739        }
16740
16741        final IWindowSession mSession;
16742
16743        final IWindow mWindow;
16744
16745        final IBinder mWindowToken;
16746
16747        final Callbacks mRootCallbacks;
16748
16749        HardwareCanvas mHardwareCanvas;
16750
16751        /**
16752         * The top view of the hierarchy.
16753         */
16754        View mRootView;
16755
16756        IBinder mPanelParentWindowToken;
16757        Surface mSurface;
16758
16759        boolean mHardwareAccelerated;
16760        boolean mHardwareAccelerationRequested;
16761        HardwareRenderer mHardwareRenderer;
16762
16763        boolean mScreenOn;
16764
16765        /**
16766         * Scale factor used by the compatibility mode
16767         */
16768        float mApplicationScale;
16769
16770        /**
16771         * Indicates whether the application is in compatibility mode
16772         */
16773        boolean mScalingRequired;
16774
16775        /**
16776         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
16777         */
16778        boolean mTurnOffWindowResizeAnim;
16779
16780        /**
16781         * Left position of this view's window
16782         */
16783        int mWindowLeft;
16784
16785        /**
16786         * Top position of this view's window
16787         */
16788        int mWindowTop;
16789
16790        /**
16791         * Indicates whether views need to use 32-bit drawing caches
16792         */
16793        boolean mUse32BitDrawingCache;
16794
16795        /**
16796         * Describes the parts of the window that are currently completely
16797         * obscured by system UI elements.
16798         */
16799        final Rect mSystemInsets = new Rect();
16800
16801        /**
16802         * For windows that are full-screen but using insets to layout inside
16803         * of the screen decorations, these are the current insets for the
16804         * content of the window.
16805         */
16806        final Rect mContentInsets = new Rect();
16807
16808        /**
16809         * For windows that are full-screen but using insets to layout inside
16810         * of the screen decorations, these are the current insets for the
16811         * actual visible parts of the window.
16812         */
16813        final Rect mVisibleInsets = new Rect();
16814
16815        /**
16816         * The internal insets given by this window.  This value is
16817         * supplied by the client (through
16818         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
16819         * be given to the window manager when changed to be used in laying
16820         * out windows behind it.
16821         */
16822        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
16823                = new ViewTreeObserver.InternalInsetsInfo();
16824
16825        /**
16826         * All views in the window's hierarchy that serve as scroll containers,
16827         * used to determine if the window can be resized or must be panned
16828         * to adjust for a soft input area.
16829         */
16830        final ArrayList<View> mScrollContainers = new ArrayList<View>();
16831
16832        final KeyEvent.DispatcherState mKeyDispatchState
16833                = new KeyEvent.DispatcherState();
16834
16835        /**
16836         * Indicates whether the view's window currently has the focus.
16837         */
16838        boolean mHasWindowFocus;
16839
16840        /**
16841         * The current visibility of the window.
16842         */
16843        int mWindowVisibility;
16844
16845        /**
16846         * Indicates the time at which drawing started to occur.
16847         */
16848        long mDrawingTime;
16849
16850        /**
16851         * Indicates whether or not ignoring the DIRTY_MASK flags.
16852         */
16853        boolean mIgnoreDirtyState;
16854
16855        /**
16856         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
16857         * to avoid clearing that flag prematurely.
16858         */
16859        boolean mSetIgnoreDirtyState = false;
16860
16861        /**
16862         * Indicates whether the view's window is currently in touch mode.
16863         */
16864        boolean mInTouchMode;
16865
16866        /**
16867         * Indicates that ViewAncestor should trigger a global layout change
16868         * the next time it performs a traversal
16869         */
16870        boolean mRecomputeGlobalAttributes;
16871
16872        /**
16873         * Always report new attributes at next traversal.
16874         */
16875        boolean mForceReportNewAttributes;
16876
16877        /**
16878         * Set during a traveral if any views want to keep the screen on.
16879         */
16880        boolean mKeepScreenOn;
16881
16882        /**
16883         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
16884         */
16885        int mSystemUiVisibility;
16886
16887        /**
16888         * Hack to force certain system UI visibility flags to be cleared.
16889         */
16890        int mDisabledSystemUiVisibility;
16891
16892        /**
16893         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
16894         * attached.
16895         */
16896        boolean mHasSystemUiListeners;
16897
16898        /**
16899         * Set if the visibility of any views has changed.
16900         */
16901        boolean mViewVisibilityChanged;
16902
16903        /**
16904         * Set to true if a view has been scrolled.
16905         */
16906        boolean mViewScrollChanged;
16907
16908        /**
16909         * Global to the view hierarchy used as a temporary for dealing with
16910         * x/y points in the transparent region computations.
16911         */
16912        final int[] mTransparentLocation = new int[2];
16913
16914        /**
16915         * Global to the view hierarchy used as a temporary for dealing with
16916         * x/y points in the ViewGroup.invalidateChild implementation.
16917         */
16918        final int[] mInvalidateChildLocation = new int[2];
16919
16920
16921        /**
16922         * Global to the view hierarchy used as a temporary for dealing with
16923         * x/y location when view is transformed.
16924         */
16925        final float[] mTmpTransformLocation = new float[2];
16926
16927        /**
16928         * The view tree observer used to dispatch global events like
16929         * layout, pre-draw, touch mode change, etc.
16930         */
16931        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
16932
16933        /**
16934         * A Canvas used by the view hierarchy to perform bitmap caching.
16935         */
16936        Canvas mCanvas;
16937
16938        /**
16939         * The view root impl.
16940         */
16941        final ViewRootImpl mViewRootImpl;
16942
16943        /**
16944         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
16945         * handler can be used to pump events in the UI events queue.
16946         */
16947        final Handler mHandler;
16948
16949        /**
16950         * Temporary for use in computing invalidate rectangles while
16951         * calling up the hierarchy.
16952         */
16953        final Rect mTmpInvalRect = new Rect();
16954
16955        /**
16956         * Temporary for use in computing hit areas with transformed views
16957         */
16958        final RectF mTmpTransformRect = new RectF();
16959
16960        /**
16961         * Temporary list for use in collecting focusable descendents of a view.
16962         */
16963        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
16964
16965        /**
16966         * The id of the window for accessibility purposes.
16967         */
16968        int mAccessibilityWindowId = View.NO_ID;
16969
16970        /**
16971         * Whether to ingore not exposed for accessibility Views when
16972         * reporting the view tree to accessibility services.
16973         */
16974        boolean mIncludeNotImportantViews;
16975
16976        /**
16977         * The drawable for highlighting accessibility focus.
16978         */
16979        Drawable mAccessibilityFocusDrawable;
16980
16981        /**
16982         * Show where the margins, bounds and layout bounds are for each view.
16983         */
16984        final boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
16985
16986        /**
16987         * Point used to compute visible regions.
16988         */
16989        final Point mPoint = new Point();
16990
16991        /**
16992         * Creates a new set of attachment information with the specified
16993         * events handler and thread.
16994         *
16995         * @param handler the events handler the view must use
16996         */
16997        AttachInfo(IWindowSession session, IWindow window,
16998                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
16999            mSession = session;
17000            mWindow = window;
17001            mWindowToken = window.asBinder();
17002            mViewRootImpl = viewRootImpl;
17003            mHandler = handler;
17004            mRootCallbacks = effectPlayer;
17005        }
17006    }
17007
17008    /**
17009     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17010     * is supported. This avoids keeping too many unused fields in most
17011     * instances of View.</p>
17012     */
17013    private static class ScrollabilityCache implements Runnable {
17014
17015        /**
17016         * Scrollbars are not visible
17017         */
17018        public static final int OFF = 0;
17019
17020        /**
17021         * Scrollbars are visible
17022         */
17023        public static final int ON = 1;
17024
17025        /**
17026         * Scrollbars are fading away
17027         */
17028        public static final int FADING = 2;
17029
17030        public boolean fadeScrollBars;
17031
17032        public int fadingEdgeLength;
17033        public int scrollBarDefaultDelayBeforeFade;
17034        public int scrollBarFadeDuration;
17035
17036        public int scrollBarSize;
17037        public ScrollBarDrawable scrollBar;
17038        public float[] interpolatorValues;
17039        public View host;
17040
17041        public final Paint paint;
17042        public final Matrix matrix;
17043        public Shader shader;
17044
17045        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17046
17047        private static final float[] OPAQUE = { 255 };
17048        private static final float[] TRANSPARENT = { 0.0f };
17049
17050        /**
17051         * When fading should start. This time moves into the future every time
17052         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17053         */
17054        public long fadeStartTime;
17055
17056
17057        /**
17058         * The current state of the scrollbars: ON, OFF, or FADING
17059         */
17060        public int state = OFF;
17061
17062        private int mLastColor;
17063
17064        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17065            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17066            scrollBarSize = configuration.getScaledScrollBarSize();
17067            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17068            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17069
17070            paint = new Paint();
17071            matrix = new Matrix();
17072            // use use a height of 1, and then wack the matrix each time we
17073            // actually use it.
17074            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17075
17076            paint.setShader(shader);
17077            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17078            this.host = host;
17079        }
17080
17081        public void setFadeColor(int color) {
17082            if (color != 0 && color != mLastColor) {
17083                mLastColor = color;
17084                color |= 0xFF000000;
17085
17086                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17087                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17088
17089                paint.setShader(shader);
17090                // Restore the default transfer mode (src_over)
17091                paint.setXfermode(null);
17092            }
17093        }
17094
17095        public void run() {
17096            long now = AnimationUtils.currentAnimationTimeMillis();
17097            if (now >= fadeStartTime) {
17098
17099                // the animation fades the scrollbars out by changing
17100                // the opacity (alpha) from fully opaque to fully
17101                // transparent
17102                int nextFrame = (int) now;
17103                int framesCount = 0;
17104
17105                Interpolator interpolator = scrollBarInterpolator;
17106
17107                // Start opaque
17108                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17109
17110                // End transparent
17111                nextFrame += scrollBarFadeDuration;
17112                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17113
17114                state = FADING;
17115
17116                // Kick off the fade animation
17117                host.invalidate(true);
17118            }
17119        }
17120    }
17121
17122    /**
17123     * Resuable callback for sending
17124     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17125     */
17126    private class SendViewScrolledAccessibilityEvent implements Runnable {
17127        public volatile boolean mIsPending;
17128
17129        public void run() {
17130            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17131            mIsPending = false;
17132        }
17133    }
17134
17135    /**
17136     * <p>
17137     * This class represents a delegate that can be registered in a {@link View}
17138     * to enhance accessibility support via composition rather via inheritance.
17139     * It is specifically targeted to widget developers that extend basic View
17140     * classes i.e. classes in package android.view, that would like their
17141     * applications to be backwards compatible.
17142     * </p>
17143     * <div class="special reference">
17144     * <h3>Developer Guides</h3>
17145     * <p>For more information about making applications accessible, read the
17146     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17147     * developer guide.</p>
17148     * </div>
17149     * <p>
17150     * A scenario in which a developer would like to use an accessibility delegate
17151     * is overriding a method introduced in a later API version then the minimal API
17152     * version supported by the application. For example, the method
17153     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17154     * in API version 4 when the accessibility APIs were first introduced. If a
17155     * developer would like his application to run on API version 4 devices (assuming
17156     * all other APIs used by the application are version 4 or lower) and take advantage
17157     * of this method, instead of overriding the method which would break the application's
17158     * backwards compatibility, he can override the corresponding method in this
17159     * delegate and register the delegate in the target View if the API version of
17160     * the system is high enough i.e. the API version is same or higher to the API
17161     * version that introduced
17162     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17163     * </p>
17164     * <p>
17165     * Here is an example implementation:
17166     * </p>
17167     * <code><pre><p>
17168     * if (Build.VERSION.SDK_INT >= 14) {
17169     *     // If the API version is equal of higher than the version in
17170     *     // which onInitializeAccessibilityNodeInfo was introduced we
17171     *     // register a delegate with a customized implementation.
17172     *     View view = findViewById(R.id.view_id);
17173     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17174     *         public void onInitializeAccessibilityNodeInfo(View host,
17175     *                 AccessibilityNodeInfo info) {
17176     *             // Let the default implementation populate the info.
17177     *             super.onInitializeAccessibilityNodeInfo(host, info);
17178     *             // Set some other information.
17179     *             info.setEnabled(host.isEnabled());
17180     *         }
17181     *     });
17182     * }
17183     * </code></pre></p>
17184     * <p>
17185     * This delegate contains methods that correspond to the accessibility methods
17186     * in View. If a delegate has been specified the implementation in View hands
17187     * off handling to the corresponding method in this delegate. The default
17188     * implementation the delegate methods behaves exactly as the corresponding
17189     * method in View for the case of no accessibility delegate been set. Hence,
17190     * to customize the behavior of a View method, clients can override only the
17191     * corresponding delegate method without altering the behavior of the rest
17192     * accessibility related methods of the host view.
17193     * </p>
17194     */
17195    public static class AccessibilityDelegate {
17196
17197        /**
17198         * Sends an accessibility event of the given type. If accessibility is not
17199         * enabled this method has no effect.
17200         * <p>
17201         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17202         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17203         * been set.
17204         * </p>
17205         *
17206         * @param host The View hosting the delegate.
17207         * @param eventType The type of the event to send.
17208         *
17209         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17210         */
17211        public void sendAccessibilityEvent(View host, int eventType) {
17212            host.sendAccessibilityEventInternal(eventType);
17213        }
17214
17215        /**
17216         * Sends an accessibility event. This method behaves exactly as
17217         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17218         * empty {@link AccessibilityEvent} and does not perform a check whether
17219         * accessibility is enabled.
17220         * <p>
17221         * The default implementation behaves as
17222         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17223         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17224         * the case of no accessibility delegate been set.
17225         * </p>
17226         *
17227         * @param host The View hosting the delegate.
17228         * @param event The event to send.
17229         *
17230         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17231         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17232         */
17233        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17234            host.sendAccessibilityEventUncheckedInternal(event);
17235        }
17236
17237        /**
17238         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17239         * to its children for adding their text content to the event.
17240         * <p>
17241         * The default implementation behaves as
17242         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17243         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17244         * the case of no accessibility delegate been set.
17245         * </p>
17246         *
17247         * @param host The View hosting the delegate.
17248         * @param event The event.
17249         * @return True if the event population was completed.
17250         *
17251         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17252         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17253         */
17254        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17255            return host.dispatchPopulateAccessibilityEventInternal(event);
17256        }
17257
17258        /**
17259         * Gives a chance to the host View to populate the accessibility event with its
17260         * text content.
17261         * <p>
17262         * The default implementation behaves as
17263         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17264         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17265         * the case of no accessibility delegate been set.
17266         * </p>
17267         *
17268         * @param host The View hosting the delegate.
17269         * @param event The accessibility event which to populate.
17270         *
17271         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17272         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17273         */
17274        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17275            host.onPopulateAccessibilityEventInternal(event);
17276        }
17277
17278        /**
17279         * Initializes an {@link AccessibilityEvent} with information about the
17280         * the host View which is the event source.
17281         * <p>
17282         * The default implementation behaves as
17283         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17284         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17285         * the case of no accessibility delegate been set.
17286         * </p>
17287         *
17288         * @param host The View hosting the delegate.
17289         * @param event The event to initialize.
17290         *
17291         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17292         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17293         */
17294        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17295            host.onInitializeAccessibilityEventInternal(event);
17296        }
17297
17298        /**
17299         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17300         * <p>
17301         * The default implementation behaves as
17302         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17303         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17304         * the case of no accessibility delegate been set.
17305         * </p>
17306         *
17307         * @param host The View hosting the delegate.
17308         * @param info The instance to initialize.
17309         *
17310         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17311         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17312         */
17313        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17314            host.onInitializeAccessibilityNodeInfoInternal(info);
17315        }
17316
17317        /**
17318         * Called when a child of the host View has requested sending an
17319         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17320         * to augment the event.
17321         * <p>
17322         * The default implementation behaves as
17323         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17324         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17325         * the case of no accessibility delegate been set.
17326         * </p>
17327         *
17328         * @param host The View hosting the delegate.
17329         * @param child The child which requests sending the event.
17330         * @param event The event to be sent.
17331         * @return True if the event should be sent
17332         *
17333         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17334         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17335         */
17336        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17337                AccessibilityEvent event) {
17338            return host.onRequestSendAccessibilityEventInternal(child, event);
17339        }
17340
17341        /**
17342         * Gets the provider for managing a virtual view hierarchy rooted at this View
17343         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17344         * that explore the window content.
17345         * <p>
17346         * The default implementation behaves as
17347         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17348         * the case of no accessibility delegate been set.
17349         * </p>
17350         *
17351         * @return The provider.
17352         *
17353         * @see AccessibilityNodeProvider
17354         */
17355        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17356            return null;
17357        }
17358    }
17359}
17360