View.java revision a90e4512ab81dcd8cdbefdd2ffa0de55fca1caa3
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.util.AttributeSet;
51import android.util.FloatProperty;
52import android.util.LocaleUtil;
53import android.util.Log;
54import android.util.Pool;
55import android.util.Poolable;
56import android.util.PoolableManager;
57import android.util.Pools;
58import android.util.Property;
59import android.util.SparseArray;
60import android.util.TypedValue;
61import android.view.ContextMenu.ContextMenuInfo;
62import android.view.AccessibilityIterators.TextSegmentIterator;
63import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
64import android.view.AccessibilityIterators.WordTextSegmentIterator;
65import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
66import android.view.accessibility.AccessibilityEvent;
67import android.view.accessibility.AccessibilityEventSource;
68import android.view.accessibility.AccessibilityManager;
69import android.view.accessibility.AccessibilityNodeInfo;
70import android.view.accessibility.AccessibilityNodeProvider;
71import android.view.animation.Animation;
72import android.view.animation.AnimationUtils;
73import android.view.animation.Transformation;
74import android.view.inputmethod.EditorInfo;
75import android.view.inputmethod.InputConnection;
76import android.view.inputmethod.InputMethodManager;
77import android.widget.ScrollBarDrawable;
78
79import static android.os.Build.VERSION_CODES.*;
80import static java.lang.Math.max;
81
82import com.android.internal.R;
83import com.android.internal.util.Predicate;
84import com.android.internal.view.menu.MenuBuilder;
85
86import java.lang.ref.WeakReference;
87import java.lang.reflect.InvocationTargetException;
88import java.lang.reflect.Method;
89import java.util.ArrayList;
90import java.util.Arrays;
91import java.util.Locale;
92import java.util.concurrent.CopyOnWriteArrayList;
93
94/**
95 * <p>
96 * This class represents the basic building block for user interface components. A View
97 * occupies a rectangular area on the screen and is responsible for drawing and
98 * event handling. View is the base class for <em>widgets</em>, which are
99 * used to create interactive UI components (buttons, text fields, etc.). The
100 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
101 * are invisible containers that hold other Views (or other ViewGroups) and define
102 * their layout properties.
103 * </p>
104 *
105 * <div class="special reference">
106 * <h3>Developer Guides</h3>
107 * <p>For information about using this class to develop your application's user interface,
108 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
109 * </div>
110 *
111 * <a name="Using"></a>
112 * <h3>Using Views</h3>
113 * <p>
114 * All of the views in a window are arranged in a single tree. You can add views
115 * either from code or by specifying a tree of views in one or more XML layout
116 * files. There are many specialized subclasses of views that act as controls or
117 * are capable of displaying text, images, or other content.
118 * </p>
119 * <p>
120 * Once you have created a tree of views, there are typically a few types of
121 * common operations you may wish to perform:
122 * <ul>
123 * <li><strong>Set properties:</strong> for example setting the text of a
124 * {@link android.widget.TextView}. The available properties and the methods
125 * that set them will vary among the different subclasses of views. Note that
126 * properties that are known at build time can be set in the XML layout
127 * files.</li>
128 * <li><strong>Set focus:</strong> The framework will handled moving focus in
129 * response to user input. To force focus to a specific view, call
130 * {@link #requestFocus}.</li>
131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
132 * that will be notified when something interesting happens to the view. For
133 * example, all views will let you set a listener to be notified when the view
134 * gains or loses focus. You can register such a listener using
135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
136 * Other view subclasses offer more specialized listeners. For example, a Button
137 * exposes a listener to notify clients when the button is clicked.</li>
138 * <li><strong>Set visibility:</strong> You can hide or show views using
139 * {@link #setVisibility(int)}.</li>
140 * </ul>
141 * </p>
142 * <p><em>
143 * Note: The Android framework is responsible for measuring, laying out and
144 * drawing views. You should not call methods that perform these actions on
145 * views yourself unless you are actually implementing a
146 * {@link android.view.ViewGroup}.
147 * </em></p>
148 *
149 * <a name="Lifecycle"></a>
150 * <h3>Implementing a Custom View</h3>
151 *
152 * <p>
153 * To implement a custom view, you will usually begin by providing overrides for
154 * some of the standard methods that the framework calls on all views. You do
155 * not need to override all of these methods. In fact, you can start by just
156 * overriding {@link #onDraw(android.graphics.Canvas)}.
157 * <table border="2" width="85%" align="center" cellpadding="5">
158 *     <thead>
159 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
160 *     </thead>
161 *
162 *     <tbody>
163 *     <tr>
164 *         <td rowspan="2">Creation</td>
165 *         <td>Constructors</td>
166 *         <td>There is a form of the constructor that are called when the view
167 *         is created from code and a form that is called when the view is
168 *         inflated from a layout file. The second form should parse and apply
169 *         any attributes defined in the layout file.
170 *         </td>
171 *     </tr>
172 *     <tr>
173 *         <td><code>{@link #onFinishInflate()}</code></td>
174 *         <td>Called after a view and all of its children has been inflated
175 *         from XML.</td>
176 *     </tr>
177 *
178 *     <tr>
179 *         <td rowspan="3">Layout</td>
180 *         <td><code>{@link #onMeasure(int, int)}</code></td>
181 *         <td>Called to determine the size requirements for this view and all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
187 *         <td>Called when this view should assign a size and position to all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
193 *         <td>Called when the size of this view has changed.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td>Drawing</td>
199 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
200 *         <td>Called when the view should render its content.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td rowspan="4">Event processing</td>
206 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
207 *         <td>Called when a new hardware key event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
212 *         <td>Called when a hardware key up event occurs.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
217 *         <td>Called when a trackball motion event occurs.
218 *         </td>
219 *     </tr>
220 *     <tr>
221 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
222 *         <td>Called when a touch screen motion event occurs.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="2">Focus</td>
228 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
229 *         <td>Called when the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
235 *         <td>Called when the window containing the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="3">Attaching</td>
241 *         <td><code>{@link #onAttachedToWindow()}</code></td>
242 *         <td>Called when the view is attached to a window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onDetachedFromWindow}</code></td>
248 *         <td>Called when the view is detached from its window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
254 *         <td>Called when the visibility of the window containing the view
255 *         has changed.
256 *         </td>
257 *     </tr>
258 *     </tbody>
259 *
260 * </table>
261 * </p>
262 *
263 * <a name="IDs"></a>
264 * <h3>IDs</h3>
265 * Views may have an integer id associated with them. These ids are typically
266 * assigned in the layout XML files, and are used to find specific views within
267 * the view tree. A common pattern is to:
268 * <ul>
269 * <li>Define a Button in the layout file and assign it a unique ID.
270 * <pre>
271 * &lt;Button
272 *     android:id="@+id/my_button"
273 *     android:layout_width="wrap_content"
274 *     android:layout_height="wrap_content"
275 *     android:text="@string/my_button_text"/&gt;
276 * </pre></li>
277 * <li>From the onCreate method of an Activity, find the Button
278 * <pre class="prettyprint">
279 *      Button myButton = (Button) findViewById(R.id.my_button);
280 * </pre></li>
281 * </ul>
282 * <p>
283 * View IDs need not be unique throughout the tree, but it is good practice to
284 * ensure that they are at least unique within the part of the tree you are
285 * searching.
286 * </p>
287 *
288 * <a name="Position"></a>
289 * <h3>Position</h3>
290 * <p>
291 * The geometry of a view is that of a rectangle. A view has a location,
292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
293 * two dimensions, expressed as a width and a height. The unit for location
294 * and dimensions is the pixel.
295 * </p>
296 *
297 * <p>
298 * It is possible to retrieve the location of a view by invoking the methods
299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
300 * coordinate of the rectangle representing the view. The latter returns the
301 * top, or Y, coordinate of the rectangle representing the view. These methods
302 * both return the location of the view relative to its parent. For instance,
303 * when getLeft() returns 20, that means the view is located 20 pixels to the
304 * right of the left edge of its direct parent.
305 * </p>
306 *
307 * <p>
308 * In addition, several convenience methods are offered to avoid unnecessary
309 * computations, namely {@link #getRight()} and {@link #getBottom()}.
310 * These methods return the coordinates of the right and bottom edges of the
311 * rectangle representing the view. For instance, calling {@link #getRight()}
312 * is similar to the following computation: <code>getLeft() + getWidth()</code>
313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
314 * </p>
315 *
316 * <a name="SizePaddingMargins"></a>
317 * <h3>Size, padding and margins</h3>
318 * <p>
319 * The size of a view is expressed with a width and a height. A view actually
320 * possess two pairs of width and height values.
321 * </p>
322 *
323 * <p>
324 * The first pair is known as <em>measured width</em> and
325 * <em>measured height</em>. These dimensions define how big a view wants to be
326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
328 * and {@link #getMeasuredHeight()}.
329 * </p>
330 *
331 * <p>
332 * The second pair is simply known as <em>width</em> and <em>height</em>, or
333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
334 * dimensions define the actual size of the view on screen, at drawing time and
335 * after layout. These values may, but do not have to, be different from the
336 * measured width and height. The width and height can be obtained by calling
337 * {@link #getWidth()} and {@link #getHeight()}.
338 * </p>
339 *
340 * <p>
341 * To measure its dimensions, a view takes into account its padding. The padding
342 * is expressed in pixels for the left, top, right and bottom parts of the view.
343 * Padding can be used to offset the content of the view by a specific amount of
344 * pixels. For instance, a left padding of 2 will push the view's content by
345 * 2 pixels to the right of the left edge. Padding can be set using the
346 * {@link #setPadding(int, int, int, int)} method and queried by calling
347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()}, {@link #getPaddingRight()},
348 * {@link #getPaddingBottom()}.
349 * </p>
350 *
351 * <p>
352 * Even though a view can define a padding, it does not provide any support for
353 * margins. However, view groups provide such a support. Refer to
354 * {@link android.view.ViewGroup} and
355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
356 * </p>
357 *
358 * <a name="Layout"></a>
359 * <h3>Layout</h3>
360 * <p>
361 * Layout is a two pass process: a measure pass and a layout pass. The measuring
362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
363 * of the view tree. Each view pushes dimension specifications down the tree
364 * during the recursion. At the end of the measure pass, every view has stored
365 * its measurements. The second pass happens in
366 * {@link #layout(int,int,int,int)} and is also top-down. During
367 * this pass each parent is responsible for positioning all of its children
368 * using the sizes computed in the measure pass.
369 * </p>
370 *
371 * <p>
372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
373 * {@link #getMeasuredHeight()} values must be set, along with those for all of
374 * that view's descendants. A view's measured width and measured height values
375 * must respect the constraints imposed by the view's parents. This guarantees
376 * that at the end of the measure pass, all parents accept all of their
377 * children's measurements. A parent view may call measure() more than once on
378 * its children. For example, the parent may measure each child once with
379 * unspecified dimensions to find out how big they want to be, then call
380 * measure() on them again with actual numbers if the sum of all the children's
381 * unconstrained sizes is too big or too small.
382 * </p>
383 *
384 * <p>
385 * The measure pass uses two classes to communicate dimensions. The
386 * {@link MeasureSpec} class is used by views to tell their parents how they
387 * want to be measured and positioned. The base LayoutParams class just
388 * describes how big the view wants to be for both width and height. For each
389 * dimension, it can specify one of:
390 * <ul>
391 * <li> an exact number
392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
393 * (minus padding)
394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
395 * enclose its content (plus padding).
396 * </ul>
397 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
399 * an X and Y value.
400 * </p>
401 *
402 * <p>
403 * MeasureSpecs are used to push requirements down the tree from parent to
404 * child. A MeasureSpec can be in one of three modes:
405 * <ul>
406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
407 * of a child view. For example, a LinearLayout may call measure() on its child
408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
409 * tall the child view wants to be given a width of 240 pixels.
410 * <li>EXACTLY: This is used by the parent to impose an exact size on the
411 * child. The child must use this size, and guarantee that all of its
412 * descendants will fit within this size.
413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
414 * child. The child must gurantee that it and all of its descendants will fit
415 * within this size.
416 * </ul>
417 * </p>
418 *
419 * <p>
420 * To intiate a layout, call {@link #requestLayout}. This method is typically
421 * called by a view on itself when it believes that is can no longer fit within
422 * its current bounds.
423 * </p>
424 *
425 * <a name="Drawing"></a>
426 * <h3>Drawing</h3>
427 * <p>
428 * Drawing is handled by walking the tree and rendering each view that
429 * intersects the invalid region. Because the tree is traversed in-order,
430 * this means that parents will draw before (i.e., behind) their children, with
431 * siblings drawn in the order they appear in the tree.
432 * If you set a background drawable for a View, then the View will draw it for you
433 * before calling back to its <code>onDraw()</code> method.
434 * </p>
435 *
436 * <p>
437 * Note that the framework will not draw views that are not in the invalid region.
438 * </p>
439 *
440 * <p>
441 * To force a view to draw, call {@link #invalidate()}.
442 * </p>
443 *
444 * <a name="EventHandlingThreading"></a>
445 * <h3>Event Handling and Threading</h3>
446 * <p>
447 * The basic cycle of a view is as follows:
448 * <ol>
449 * <li>An event comes in and is dispatched to the appropriate view. The view
450 * handles the event and notifies any listeners.</li>
451 * <li>If in the course of processing the event, the view's bounds may need
452 * to be changed, the view will call {@link #requestLayout()}.</li>
453 * <li>Similarly, if in the course of processing the event the view's appearance
454 * may need to be changed, the view will call {@link #invalidate()}.</li>
455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
456 * the framework will take care of measuring, laying out, and drawing the tree
457 * as appropriate.</li>
458 * </ol>
459 * </p>
460 *
461 * <p><em>Note: The entire view tree is single threaded. You must always be on
462 * the UI thread when calling any method on any view.</em>
463 * If you are doing work on other threads and want to update the state of a view
464 * from that thread, you should use a {@link Handler}.
465 * </p>
466 *
467 * <a name="FocusHandling"></a>
468 * <h3>Focus Handling</h3>
469 * <p>
470 * The framework will handle routine focus movement in response to user input.
471 * This includes changing the focus as views are removed or hidden, or as new
472 * views become available. Views indicate their willingness to take focus
473 * through the {@link #isFocusable} method. To change whether a view can take
474 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
476 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
477 * </p>
478 * <p>
479 * Focus movement is based on an algorithm which finds the nearest neighbor in a
480 * given direction. In rare cases, the default algorithm may not match the
481 * intended behavior of the developer. In these situations, you can provide
482 * explicit overrides by using these XML attributes in the layout file:
483 * <pre>
484 * nextFocusDown
485 * nextFocusLeft
486 * nextFocusRight
487 * nextFocusUp
488 * </pre>
489 * </p>
490 *
491 *
492 * <p>
493 * To get a particular view to take focus, call {@link #requestFocus()}.
494 * </p>
495 *
496 * <a name="TouchMode"></a>
497 * <h3>Touch Mode</h3>
498 * <p>
499 * When a user is navigating a user interface via directional keys such as a D-pad, it is
500 * necessary to give focus to actionable items such as buttons so the user can see
501 * what will take input.  If the device has touch capabilities, however, and the user
502 * begins interacting with the interface by touching it, it is no longer necessary to
503 * always highlight, or give focus to, a particular view.  This motivates a mode
504 * for interaction named 'touch mode'.
505 * </p>
506 * <p>
507 * For a touch capable device, once the user touches the screen, the device
508 * will enter touch mode.  From this point onward, only views for which
509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
510 * Other views that are touchable, like buttons, will not take focus when touched; they will
511 * only fire the on click listeners.
512 * </p>
513 * <p>
514 * Any time a user hits a directional key, such as a D-pad direction, the view device will
515 * exit touch mode, and find a view to take focus, so that the user may resume interacting
516 * with the user interface without touching the screen again.
517 * </p>
518 * <p>
519 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
520 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
521 * </p>
522 *
523 * <a name="Scrolling"></a>
524 * <h3>Scrolling</h3>
525 * <p>
526 * The framework provides basic support for views that wish to internally
527 * scroll their content. This includes keeping track of the X and Y scroll
528 * offset as well as mechanisms for drawing scrollbars. See
529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
530 * {@link #awakenScrollBars()} for more details.
531 * </p>
532 *
533 * <a name="Tags"></a>
534 * <h3>Tags</h3>
535 * <p>
536 * Unlike IDs, tags are not used to identify views. Tags are essentially an
537 * extra piece of information that can be associated with a view. They are most
538 * often used as a convenience to store data related to views in the views
539 * themselves rather than by putting them in a separate structure.
540 * </p>
541 *
542 * <a name="Properties"></a>
543 * <h3>Properties</h3>
544 * <p>
545 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
546 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
547 * available both in the {@link Property} form as well as in similarly-named setter/getter
548 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
549 * be used to set persistent state associated with these rendering-related properties on the view.
550 * The properties and methods can also be used in conjunction with
551 * {@link android.animation.Animator Animator}-based animations, described more in the
552 * <a href="#Animation">Animation</a> section.
553 * </p>
554 *
555 * <a name="Animation"></a>
556 * <h3>Animation</h3>
557 * <p>
558 * Starting with Android 3.0, the preferred way of animating views is to use the
559 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
560 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
561 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
562 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
563 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
564 * makes animating these View properties particularly easy and efficient.
565 * </p>
566 * <p>
567 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
568 * You can attach an {@link Animation} object to a view using
569 * {@link #setAnimation(Animation)} or
570 * {@link #startAnimation(Animation)}. The animation can alter the scale,
571 * rotation, translation and alpha of a view over time. If the animation is
572 * attached to a view that has children, the animation will affect the entire
573 * subtree rooted by that node. When an animation is started, the framework will
574 * take care of redrawing the appropriate views until the animation completes.
575 * </p>
576 *
577 * <a name="Security"></a>
578 * <h3>Security</h3>
579 * <p>
580 * Sometimes it is essential that an application be able to verify that an action
581 * is being performed with the full knowledge and consent of the user, such as
582 * granting a permission request, making a purchase or clicking on an advertisement.
583 * Unfortunately, a malicious application could try to spoof the user into
584 * performing these actions, unaware, by concealing the intended purpose of the view.
585 * As a remedy, the framework offers a touch filtering mechanism that can be used to
586 * improve the security of views that provide access to sensitive functionality.
587 * </p><p>
588 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
589 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
590 * will discard touches that are received whenever the view's window is obscured by
591 * another visible window.  As a result, the view will not receive touches whenever a
592 * toast, dialog or other window appears above the view's window.
593 * </p><p>
594 * For more fine-grained control over security, consider overriding the
595 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
596 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
597 * </p>
598 *
599 * @attr ref android.R.styleable#View_alpha
600 * @attr ref android.R.styleable#View_background
601 * @attr ref android.R.styleable#View_clickable
602 * @attr ref android.R.styleable#View_contentDescription
603 * @attr ref android.R.styleable#View_drawingCacheQuality
604 * @attr ref android.R.styleable#View_duplicateParentState
605 * @attr ref android.R.styleable#View_id
606 * @attr ref android.R.styleable#View_requiresFadingEdge
607 * @attr ref android.R.styleable#View_fadeScrollbars
608 * @attr ref android.R.styleable#View_fadingEdgeLength
609 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
610 * @attr ref android.R.styleable#View_fitsSystemWindows
611 * @attr ref android.R.styleable#View_isScrollContainer
612 * @attr ref android.R.styleable#View_focusable
613 * @attr ref android.R.styleable#View_focusableInTouchMode
614 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
615 * @attr ref android.R.styleable#View_keepScreenOn
616 * @attr ref android.R.styleable#View_layerType
617 * @attr ref android.R.styleable#View_longClickable
618 * @attr ref android.R.styleable#View_minHeight
619 * @attr ref android.R.styleable#View_minWidth
620 * @attr ref android.R.styleable#View_nextFocusDown
621 * @attr ref android.R.styleable#View_nextFocusLeft
622 * @attr ref android.R.styleable#View_nextFocusRight
623 * @attr ref android.R.styleable#View_nextFocusUp
624 * @attr ref android.R.styleable#View_onClick
625 * @attr ref android.R.styleable#View_padding
626 * @attr ref android.R.styleable#View_paddingBottom
627 * @attr ref android.R.styleable#View_paddingLeft
628 * @attr ref android.R.styleable#View_paddingRight
629 * @attr ref android.R.styleable#View_paddingTop
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_transformPivotX
652 * @attr ref android.R.styleable#View_transformPivotY
653 * @attr ref android.R.styleable#View_translationX
654 * @attr ref android.R.styleable#View_translationY
655 * @attr ref android.R.styleable#View_visibility
656 *
657 * @see android.view.ViewGroup
658 */
659public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
660        AccessibilityEventSource {
661    private static final boolean DBG = false;
662
663    /**
664     * The logging tag used by this class with android.util.Log.
665     */
666    protected static final String VIEW_LOG_TAG = "View";
667
668    /**
669     * When set to true, apps will draw debugging information about their layouts.
670     *
671     * @hide
672     */
673    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
674
675    /**
676     * Used to mark a View that has no ID.
677     */
678    public static final int NO_ID = -1;
679
680    /**
681     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
682     * calling setFlags.
683     */
684    private static final int NOT_FOCUSABLE = 0x00000000;
685
686    /**
687     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
688     * setFlags.
689     */
690    private static final int FOCUSABLE = 0x00000001;
691
692    /**
693     * Mask for use with setFlags indicating bits used for focus.
694     */
695    private static final int FOCUSABLE_MASK = 0x00000001;
696
697    /**
698     * This view will adjust its padding to fit sytem windows (e.g. status bar)
699     */
700    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
701
702    /**
703     * This view is visible.
704     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
705     * android:visibility}.
706     */
707    public static final int VISIBLE = 0x00000000;
708
709    /**
710     * This view is invisible, but it still takes up space for layout purposes.
711     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
712     * android:visibility}.
713     */
714    public static final int INVISIBLE = 0x00000004;
715
716    /**
717     * This view is invisible, and it doesn't take any space for layout
718     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
719     * android:visibility}.
720     */
721    public static final int GONE = 0x00000008;
722
723    /**
724     * Mask for use with setFlags indicating bits used for visibility.
725     * {@hide}
726     */
727    static final int VISIBILITY_MASK = 0x0000000C;
728
729    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
730
731    /**
732     * This view is enabled. Interpretation varies by subclass.
733     * Use with ENABLED_MASK when calling setFlags.
734     * {@hide}
735     */
736    static final int ENABLED = 0x00000000;
737
738    /**
739     * This view is disabled. Interpretation varies by subclass.
740     * Use with ENABLED_MASK when calling setFlags.
741     * {@hide}
742     */
743    static final int DISABLED = 0x00000020;
744
745   /**
746    * Mask for use with setFlags indicating bits used for indicating whether
747    * this view is enabled
748    * {@hide}
749    */
750    static final int ENABLED_MASK = 0x00000020;
751
752    /**
753     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
754     * called and further optimizations will be performed. It is okay to have
755     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
756     * {@hide}
757     */
758    static final int WILL_NOT_DRAW = 0x00000080;
759
760    /**
761     * Mask for use with setFlags indicating bits used for indicating whether
762     * this view is will draw
763     * {@hide}
764     */
765    static final int DRAW_MASK = 0x00000080;
766
767    /**
768     * <p>This view doesn't show scrollbars.</p>
769     * {@hide}
770     */
771    static final int SCROLLBARS_NONE = 0x00000000;
772
773    /**
774     * <p>This view shows horizontal scrollbars.</p>
775     * {@hide}
776     */
777    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
778
779    /**
780     * <p>This view shows vertical scrollbars.</p>
781     * {@hide}
782     */
783    static final int SCROLLBARS_VERTICAL = 0x00000200;
784
785    /**
786     * <p>Mask for use with setFlags indicating bits used for indicating which
787     * scrollbars are enabled.</p>
788     * {@hide}
789     */
790    static final int SCROLLBARS_MASK = 0x00000300;
791
792    /**
793     * Indicates that the view should filter touches when its window is obscured.
794     * Refer to the class comments for more information about this security feature.
795     * {@hide}
796     */
797    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
798
799    /**
800     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
801     * that they are optional and should be skipped if the window has
802     * requested system UI flags that ignore those insets for layout.
803     */
804    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
805
806    /**
807     * <p>This view doesn't show fading edges.</p>
808     * {@hide}
809     */
810    static final int FADING_EDGE_NONE = 0x00000000;
811
812    /**
813     * <p>This view shows horizontal fading edges.</p>
814     * {@hide}
815     */
816    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
817
818    /**
819     * <p>This view shows vertical fading edges.</p>
820     * {@hide}
821     */
822    static final int FADING_EDGE_VERTICAL = 0x00002000;
823
824    /**
825     * <p>Mask for use with setFlags indicating bits used for indicating which
826     * fading edges are enabled.</p>
827     * {@hide}
828     */
829    static final int FADING_EDGE_MASK = 0x00003000;
830
831    /**
832     * <p>Indicates this view can be clicked. When clickable, a View reacts
833     * to clicks by notifying the OnClickListener.<p>
834     * {@hide}
835     */
836    static final int CLICKABLE = 0x00004000;
837
838    /**
839     * <p>Indicates this view is caching its drawing into a bitmap.</p>
840     * {@hide}
841     */
842    static final int DRAWING_CACHE_ENABLED = 0x00008000;
843
844    /**
845     * <p>Indicates that no icicle should be saved for this view.<p>
846     * {@hide}
847     */
848    static final int SAVE_DISABLED = 0x000010000;
849
850    /**
851     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
852     * property.</p>
853     * {@hide}
854     */
855    static final int SAVE_DISABLED_MASK = 0x000010000;
856
857    /**
858     * <p>Indicates that no drawing cache should ever be created for this view.<p>
859     * {@hide}
860     */
861    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
862
863    /**
864     * <p>Indicates this view can take / keep focus when int touch mode.</p>
865     * {@hide}
866     */
867    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
868
869    /**
870     * <p>Enables low quality mode for the drawing cache.</p>
871     */
872    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
873
874    /**
875     * <p>Enables high quality mode for the drawing cache.</p>
876     */
877    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
878
879    /**
880     * <p>Enables automatic quality mode for the drawing cache.</p>
881     */
882    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
883
884    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
885            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
886    };
887
888    /**
889     * <p>Mask for use with setFlags indicating bits used for the cache
890     * quality property.</p>
891     * {@hide}
892     */
893    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
894
895    /**
896     * <p>
897     * Indicates this view can be long clicked. When long clickable, a View
898     * reacts to long clicks by notifying the OnLongClickListener or showing a
899     * context menu.
900     * </p>
901     * {@hide}
902     */
903    static final int LONG_CLICKABLE = 0x00200000;
904
905    /**
906     * <p>Indicates that this view gets its drawable states from its direct parent
907     * and ignores its original internal states.</p>
908     *
909     * @hide
910     */
911    static final int DUPLICATE_PARENT_STATE = 0x00400000;
912
913    /**
914     * The scrollbar style to display the scrollbars inside the content area,
915     * without increasing the padding. The scrollbars will be overlaid with
916     * translucency on the view's content.
917     */
918    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
919
920    /**
921     * The scrollbar style to display the scrollbars inside the padded area,
922     * increasing the padding of the view. The scrollbars will not overlap the
923     * content area of the view.
924     */
925    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
926
927    /**
928     * The scrollbar style to display the scrollbars at the edge of the view,
929     * without increasing the padding. The scrollbars will be overlaid with
930     * translucency.
931     */
932    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
933
934    /**
935     * The scrollbar style to display the scrollbars at the edge of the view,
936     * increasing the padding of the view. The scrollbars will only overlap the
937     * background, if any.
938     */
939    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
940
941    /**
942     * Mask to check if the scrollbar style is overlay or inset.
943     * {@hide}
944     */
945    static final int SCROLLBARS_INSET_MASK = 0x01000000;
946
947    /**
948     * Mask to check if the scrollbar style is inside or outside.
949     * {@hide}
950     */
951    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
952
953    /**
954     * Mask for scrollbar style.
955     * {@hide}
956     */
957    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
958
959    /**
960     * View flag indicating that the screen should remain on while the
961     * window containing this view is visible to the user.  This effectively
962     * takes care of automatically setting the WindowManager's
963     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
964     */
965    public static final int KEEP_SCREEN_ON = 0x04000000;
966
967    /**
968     * View flag indicating whether this view should have sound effects enabled
969     * for events such as clicking and touching.
970     */
971    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
972
973    /**
974     * View flag indicating whether this view should have haptic feedback
975     * enabled for events such as long presses.
976     */
977    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
978
979    /**
980     * <p>Indicates that the view hierarchy should stop saving state when
981     * it reaches this view.  If state saving is initiated immediately at
982     * the view, it will be allowed.
983     * {@hide}
984     */
985    static final int PARENT_SAVE_DISABLED = 0x20000000;
986
987    /**
988     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
989     * {@hide}
990     */
991    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
992
993    /**
994     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
995     * should add all focusable Views regardless if they are focusable in touch mode.
996     */
997    public static final int FOCUSABLES_ALL = 0x00000000;
998
999    /**
1000     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1001     * should add only Views focusable in touch mode.
1002     */
1003    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1004
1005    /**
1006     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1007     * should add only accessibility focusable Views.
1008     *
1009     * @hide
1010     */
1011    public static final int FOCUSABLES_ACCESSIBILITY = 0x00000002;
1012
1013    /**
1014     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1015     * item.
1016     */
1017    public static final int FOCUS_BACKWARD = 0x00000001;
1018
1019    /**
1020     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1021     * item.
1022     */
1023    public static final int FOCUS_FORWARD = 0x00000002;
1024
1025    /**
1026     * Use with {@link #focusSearch(int)}. Move focus to the left.
1027     */
1028    public static final int FOCUS_LEFT = 0x00000011;
1029
1030    /**
1031     * Use with {@link #focusSearch(int)}. Move focus up.
1032     */
1033    public static final int FOCUS_UP = 0x00000021;
1034
1035    /**
1036     * Use with {@link #focusSearch(int)}. Move focus to the right.
1037     */
1038    public static final int FOCUS_RIGHT = 0x00000042;
1039
1040    /**
1041     * Use with {@link #focusSearch(int)}. Move focus down.
1042     */
1043    public static final int FOCUS_DOWN = 0x00000082;
1044
1045    // Accessibility focus directions.
1046
1047    /**
1048     * The accessibility focus which is the current user position when
1049     * interacting with the accessibility framework.
1050     */
1051    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1052
1053    /**
1054     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1055     */
1056    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1057
1058    /**
1059     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1060     */
1061    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1062
1063    /**
1064     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1065     */
1066    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1067
1068    /**
1069     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1070     */
1071    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1072
1073    /**
1074     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1075     */
1076    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1077
1078    /**
1079     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1080     */
1081    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1082
1083    /**
1084     * Bits of {@link #getMeasuredWidthAndState()} and
1085     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1086     */
1087    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1088
1089    /**
1090     * Bits of {@link #getMeasuredWidthAndState()} and
1091     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1092     */
1093    public static final int MEASURED_STATE_MASK = 0xff000000;
1094
1095    /**
1096     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1097     * for functions that combine both width and height into a single int,
1098     * such as {@link #getMeasuredState()} and the childState argument of
1099     * {@link #resolveSizeAndState(int, int, int)}.
1100     */
1101    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1102
1103    /**
1104     * Bit of {@link #getMeasuredWidthAndState()} and
1105     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1106     * is smaller that the space the view would like to have.
1107     */
1108    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1109
1110    /**
1111     * Base View state sets
1112     */
1113    // Singles
1114    /**
1115     * Indicates the view has no states set. States are used with
1116     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1117     * view depending on its state.
1118     *
1119     * @see android.graphics.drawable.Drawable
1120     * @see #getDrawableState()
1121     */
1122    protected static final int[] EMPTY_STATE_SET;
1123    /**
1124     * Indicates the view is enabled. States are used with
1125     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1126     * view depending on its state.
1127     *
1128     * @see android.graphics.drawable.Drawable
1129     * @see #getDrawableState()
1130     */
1131    protected static final int[] ENABLED_STATE_SET;
1132    /**
1133     * Indicates the view is focused. States are used with
1134     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1135     * view depending on its state.
1136     *
1137     * @see android.graphics.drawable.Drawable
1138     * @see #getDrawableState()
1139     */
1140    protected static final int[] FOCUSED_STATE_SET;
1141    /**
1142     * Indicates the view is selected. States are used with
1143     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1144     * view depending on its state.
1145     *
1146     * @see android.graphics.drawable.Drawable
1147     * @see #getDrawableState()
1148     */
1149    protected static final int[] SELECTED_STATE_SET;
1150    /**
1151     * Indicates the view is pressed. States are used with
1152     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1153     * view depending on its state.
1154     *
1155     * @see android.graphics.drawable.Drawable
1156     * @see #getDrawableState()
1157     * @hide
1158     */
1159    protected static final int[] PRESSED_STATE_SET;
1160    /**
1161     * Indicates the view's window has focus. States are used with
1162     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1163     * view depending on its state.
1164     *
1165     * @see android.graphics.drawable.Drawable
1166     * @see #getDrawableState()
1167     */
1168    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1169    // Doubles
1170    /**
1171     * Indicates the view is enabled and has the focus.
1172     *
1173     * @see #ENABLED_STATE_SET
1174     * @see #FOCUSED_STATE_SET
1175     */
1176    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1177    /**
1178     * Indicates the view is enabled and selected.
1179     *
1180     * @see #ENABLED_STATE_SET
1181     * @see #SELECTED_STATE_SET
1182     */
1183    protected static final int[] ENABLED_SELECTED_STATE_SET;
1184    /**
1185     * Indicates the view is enabled and that its window has focus.
1186     *
1187     * @see #ENABLED_STATE_SET
1188     * @see #WINDOW_FOCUSED_STATE_SET
1189     */
1190    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1191    /**
1192     * Indicates the view is focused and selected.
1193     *
1194     * @see #FOCUSED_STATE_SET
1195     * @see #SELECTED_STATE_SET
1196     */
1197    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1198    /**
1199     * Indicates the view has the focus and that its window has the focus.
1200     *
1201     * @see #FOCUSED_STATE_SET
1202     * @see #WINDOW_FOCUSED_STATE_SET
1203     */
1204    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1205    /**
1206     * Indicates the view is selected and that its window has the focus.
1207     *
1208     * @see #SELECTED_STATE_SET
1209     * @see #WINDOW_FOCUSED_STATE_SET
1210     */
1211    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1212    // Triples
1213    /**
1214     * Indicates the view is enabled, focused and selected.
1215     *
1216     * @see #ENABLED_STATE_SET
1217     * @see #FOCUSED_STATE_SET
1218     * @see #SELECTED_STATE_SET
1219     */
1220    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1221    /**
1222     * Indicates the view is enabled, focused and its window has the focus.
1223     *
1224     * @see #ENABLED_STATE_SET
1225     * @see #FOCUSED_STATE_SET
1226     * @see #WINDOW_FOCUSED_STATE_SET
1227     */
1228    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1229    /**
1230     * Indicates the view is enabled, selected and its window has the focus.
1231     *
1232     * @see #ENABLED_STATE_SET
1233     * @see #SELECTED_STATE_SET
1234     * @see #WINDOW_FOCUSED_STATE_SET
1235     */
1236    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1237    /**
1238     * Indicates the view is focused, selected and its window has the focus.
1239     *
1240     * @see #FOCUSED_STATE_SET
1241     * @see #SELECTED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is enabled, focused, selected and its window
1247     * has the focus.
1248     *
1249     * @see #ENABLED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     * @see #SELECTED_STATE_SET
1252     * @see #WINDOW_FOCUSED_STATE_SET
1253     */
1254    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1255    /**
1256     * Indicates the view is pressed and its window has the focus.
1257     *
1258     * @see #PRESSED_STATE_SET
1259     * @see #WINDOW_FOCUSED_STATE_SET
1260     */
1261    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1262    /**
1263     * Indicates the view is pressed and selected.
1264     *
1265     * @see #PRESSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed and focused.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #FOCUSED_STATE_SET
1282     */
1283    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1284    /**
1285     * Indicates the view is pressed, focused and its window has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #FOCUSED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed, focused and selected.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #SELECTED_STATE_SET
1297     * @see #FOCUSED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, focused, selected and its window has the focus.
1302     *
1303     * @see #PRESSED_STATE_SET
1304     * @see #FOCUSED_STATE_SET
1305     * @see #SELECTED_STATE_SET
1306     * @see #WINDOW_FOCUSED_STATE_SET
1307     */
1308    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1309    /**
1310     * Indicates the view is pressed and enabled.
1311     *
1312     * @see #PRESSED_STATE_SET
1313     * @see #ENABLED_STATE_SET
1314     */
1315    protected static final int[] PRESSED_ENABLED_STATE_SET;
1316    /**
1317     * Indicates the view is pressed, enabled and its window has the focus.
1318     *
1319     * @see #PRESSED_STATE_SET
1320     * @see #ENABLED_STATE_SET
1321     * @see #WINDOW_FOCUSED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, enabled and selected.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #ENABLED_STATE_SET
1329     * @see #SELECTED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, enabled, selected and its window has the
1334     * focus.
1335     *
1336     * @see #PRESSED_STATE_SET
1337     * @see #ENABLED_STATE_SET
1338     * @see #SELECTED_STATE_SET
1339     * @see #WINDOW_FOCUSED_STATE_SET
1340     */
1341    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1342    /**
1343     * Indicates the view is pressed, enabled and focused.
1344     *
1345     * @see #PRESSED_STATE_SET
1346     * @see #ENABLED_STATE_SET
1347     * @see #FOCUSED_STATE_SET
1348     */
1349    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1350    /**
1351     * Indicates the view is pressed, enabled, focused and its window has the
1352     * focus.
1353     *
1354     * @see #PRESSED_STATE_SET
1355     * @see #ENABLED_STATE_SET
1356     * @see #FOCUSED_STATE_SET
1357     * @see #WINDOW_FOCUSED_STATE_SET
1358     */
1359    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1360    /**
1361     * Indicates the view is pressed, enabled, focused and selected.
1362     *
1363     * @see #PRESSED_STATE_SET
1364     * @see #ENABLED_STATE_SET
1365     * @see #SELECTED_STATE_SET
1366     * @see #FOCUSED_STATE_SET
1367     */
1368    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1369    /**
1370     * Indicates the view is pressed, enabled, focused, selected and its window
1371     * has the focus.
1372     *
1373     * @see #PRESSED_STATE_SET
1374     * @see #ENABLED_STATE_SET
1375     * @see #SELECTED_STATE_SET
1376     * @see #FOCUSED_STATE_SET
1377     * @see #WINDOW_FOCUSED_STATE_SET
1378     */
1379    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1380
1381    /**
1382     * The order here is very important to {@link #getDrawableState()}
1383     */
1384    private static final int[][] VIEW_STATE_SETS;
1385
1386    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1387    static final int VIEW_STATE_SELECTED = 1 << 1;
1388    static final int VIEW_STATE_FOCUSED = 1 << 2;
1389    static final int VIEW_STATE_ENABLED = 1 << 3;
1390    static final int VIEW_STATE_PRESSED = 1 << 4;
1391    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1392    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1393    static final int VIEW_STATE_HOVERED = 1 << 7;
1394    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1395    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1396
1397    static final int[] VIEW_STATE_IDS = new int[] {
1398        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1399        R.attr.state_selected,          VIEW_STATE_SELECTED,
1400        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1401        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1402        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1403        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1404        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1405        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1406        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1407        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1408    };
1409
1410    static {
1411        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1412            throw new IllegalStateException(
1413                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1414        }
1415        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1416        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1417            int viewState = R.styleable.ViewDrawableStates[i];
1418            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1419                if (VIEW_STATE_IDS[j] == viewState) {
1420                    orderedIds[i * 2] = viewState;
1421                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1422                }
1423            }
1424        }
1425        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1426        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1427        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1428            int numBits = Integer.bitCount(i);
1429            int[] set = new int[numBits];
1430            int pos = 0;
1431            for (int j = 0; j < orderedIds.length; j += 2) {
1432                if ((i & orderedIds[j+1]) != 0) {
1433                    set[pos++] = orderedIds[j];
1434                }
1435            }
1436            VIEW_STATE_SETS[i] = set;
1437        }
1438
1439        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1440        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1441        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1442        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1444        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1445        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1447        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1449        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1451                | VIEW_STATE_FOCUSED];
1452        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1453        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1455        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1457        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_ENABLED];
1460        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1462        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1464                | VIEW_STATE_ENABLED];
1465        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1467                | VIEW_STATE_ENABLED];
1468        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1471
1472        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1473        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1475        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1477        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1479                | VIEW_STATE_PRESSED];
1480        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1482        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1483                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1484                | VIEW_STATE_PRESSED];
1485        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1486                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1487                | VIEW_STATE_PRESSED];
1488        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1489                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1490                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1491        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1492                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1493        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1494                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1495                | VIEW_STATE_PRESSED];
1496        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1497                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1498                | VIEW_STATE_PRESSED];
1499        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1501                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1502        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1504                | VIEW_STATE_PRESSED];
1505        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1507                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1508        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1509                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1510                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1511        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1512                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1513                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1514                | VIEW_STATE_PRESSED];
1515    }
1516
1517    /**
1518     * Accessibility event types that are dispatched for text population.
1519     */
1520    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1521            AccessibilityEvent.TYPE_VIEW_CLICKED
1522            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1523            | AccessibilityEvent.TYPE_VIEW_SELECTED
1524            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1525            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1526            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1527            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1528            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1529            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1530            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1531            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
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     * @hide
1598     */
1599    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1600
1601    /**
1602     * The view's tag.
1603     * {@hide}
1604     *
1605     * @see #setTag(Object)
1606     * @see #getTag()
1607     */
1608    protected Object mTag;
1609
1610    // for mPrivateFlags:
1611    /** {@hide} */
1612    static final int WANTS_FOCUS                    = 0x00000001;
1613    /** {@hide} */
1614    static final int FOCUSED                        = 0x00000002;
1615    /** {@hide} */
1616    static final int SELECTED                       = 0x00000004;
1617    /** {@hide} */
1618    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1619    /** {@hide} */
1620    static final int HAS_BOUNDS                     = 0x00000010;
1621    /** {@hide} */
1622    static final int DRAWN                          = 0x00000020;
1623    /**
1624     * When this flag is set, this view is running an animation on behalf of its
1625     * children and should therefore not cancel invalidate requests, even if they
1626     * lie outside of this view's bounds.
1627     *
1628     * {@hide}
1629     */
1630    static final int DRAW_ANIMATION                 = 0x00000040;
1631    /** {@hide} */
1632    static final int SKIP_DRAW                      = 0x00000080;
1633    /** {@hide} */
1634    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1635    /** {@hide} */
1636    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1637    /** {@hide} */
1638    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1639    /** {@hide} */
1640    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1641    /** {@hide} */
1642    static final int FORCE_LAYOUT                   = 0x00001000;
1643    /** {@hide} */
1644    static final int LAYOUT_REQUIRED                = 0x00002000;
1645
1646    private static final int PRESSED                = 0x00004000;
1647
1648    /** {@hide} */
1649    static final int DRAWING_CACHE_VALID            = 0x00008000;
1650    /**
1651     * Flag used to indicate that this view should be drawn once more (and only once
1652     * more) after its animation has completed.
1653     * {@hide}
1654     */
1655    static final int ANIMATION_STARTED              = 0x00010000;
1656
1657    private static final int SAVE_STATE_CALLED      = 0x00020000;
1658
1659    /**
1660     * Indicates that the View returned true when onSetAlpha() was called and that
1661     * the alpha must be restored.
1662     * {@hide}
1663     */
1664    static final int ALPHA_SET                      = 0x00040000;
1665
1666    /**
1667     * Set by {@link #setScrollContainer(boolean)}.
1668     */
1669    static final int SCROLL_CONTAINER               = 0x00080000;
1670
1671    /**
1672     * Set by {@link #setScrollContainer(boolean)}.
1673     */
1674    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1675
1676    /**
1677     * View flag indicating whether this view was invalidated (fully or partially.)
1678     *
1679     * @hide
1680     */
1681    static final int DIRTY                          = 0x00200000;
1682
1683    /**
1684     * View flag indicating whether this view was invalidated by an opaque
1685     * invalidate request.
1686     *
1687     * @hide
1688     */
1689    static final int DIRTY_OPAQUE                   = 0x00400000;
1690
1691    /**
1692     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1693     *
1694     * @hide
1695     */
1696    static final int DIRTY_MASK                     = 0x00600000;
1697
1698    /**
1699     * Indicates whether the background is opaque.
1700     *
1701     * @hide
1702     */
1703    static final int OPAQUE_BACKGROUND              = 0x00800000;
1704
1705    /**
1706     * Indicates whether the scrollbars are opaque.
1707     *
1708     * @hide
1709     */
1710    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1711
1712    /**
1713     * Indicates whether the view is opaque.
1714     *
1715     * @hide
1716     */
1717    static final int OPAQUE_MASK                    = 0x01800000;
1718
1719    /**
1720     * Indicates a prepressed state;
1721     * the short time between ACTION_DOWN and recognizing
1722     * a 'real' press. Prepressed is used to recognize quick taps
1723     * even when they are shorter than ViewConfiguration.getTapTimeout().
1724     *
1725     * @hide
1726     */
1727    private static final int PREPRESSED             = 0x02000000;
1728
1729    /**
1730     * Indicates whether the view is temporarily detached.
1731     *
1732     * @hide
1733     */
1734    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1735
1736    /**
1737     * Indicates that we should awaken scroll bars once attached
1738     *
1739     * @hide
1740     */
1741    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1742
1743    /**
1744     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1745     * @hide
1746     */
1747    private static final int HOVERED              = 0x10000000;
1748
1749    /**
1750     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1751     * for transform operations
1752     *
1753     * @hide
1754     */
1755    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1756
1757    /** {@hide} */
1758    static final int ACTIVATED                    = 0x40000000;
1759
1760    /**
1761     * Indicates that this view was specifically invalidated, not just dirtied because some
1762     * child view was invalidated. The flag is used to determine when we need to recreate
1763     * a view's display list (as opposed to just returning a reference to its existing
1764     * display list).
1765     *
1766     * @hide
1767     */
1768    static final int INVALIDATED                  = 0x80000000;
1769
1770    /* Masks for mPrivateFlags2 */
1771
1772    /**
1773     * Indicates that this view has reported that it can accept the current drag's content.
1774     * Cleared when the drag operation concludes.
1775     * @hide
1776     */
1777    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1778
1779    /**
1780     * Indicates that this view is currently directly under the drag location in a
1781     * drag-and-drop operation involving content that it can accept.  Cleared when
1782     * the drag exits the view, or when the drag operation concludes.
1783     * @hide
1784     */
1785    static final int DRAG_HOVERED                 = 0x00000002;
1786
1787    /**
1788     * Horizontal layout direction of this view is from Left to Right.
1789     * Use with {@link #setLayoutDirection}.
1790     * @hide
1791     */
1792    public static final int LAYOUT_DIRECTION_LTR = 0;
1793
1794    /**
1795     * Horizontal layout direction of this view is from Right to Left.
1796     * Use with {@link #setLayoutDirection}.
1797     * @hide
1798     */
1799    public static final int LAYOUT_DIRECTION_RTL = 1;
1800
1801    /**
1802     * Horizontal layout direction of this view is inherited from its parent.
1803     * Use with {@link #setLayoutDirection}.
1804     * @hide
1805     */
1806    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1807
1808    /**
1809     * Horizontal layout direction of this view is from deduced from the default language
1810     * script for the locale. Use with {@link #setLayoutDirection}.
1811     * @hide
1812     */
1813    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1814
1815    /**
1816     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1817     * @hide
1818     */
1819    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1820
1821    /**
1822     * Mask for use with private flags indicating bits used for horizontal layout direction.
1823     * @hide
1824     */
1825    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1826
1827    /**
1828     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1829     * right-to-left direction.
1830     * @hide
1831     */
1832    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1833
1834    /**
1835     * Indicates whether the view horizontal layout direction has been resolved.
1836     * @hide
1837     */
1838    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1839
1840    /**
1841     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1842     * @hide
1843     */
1844    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1845
1846    /*
1847     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1848     * flag value.
1849     * @hide
1850     */
1851    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1852            LAYOUT_DIRECTION_LTR,
1853            LAYOUT_DIRECTION_RTL,
1854            LAYOUT_DIRECTION_INHERIT,
1855            LAYOUT_DIRECTION_LOCALE
1856    };
1857
1858    /**
1859     * Default horizontal layout direction.
1860     * @hide
1861     */
1862    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1863
1864    /**
1865     * Indicates that the view is tracking some sort of transient state
1866     * that the app should not need to be aware of, but that the framework
1867     * should take special care to preserve.
1868     *
1869     * @hide
1870     */
1871    static final int HAS_TRANSIENT_STATE = 0x00000100;
1872
1873
1874    /**
1875     * Text direction is inherited thru {@link ViewGroup}
1876     * @hide
1877     */
1878    public static final int TEXT_DIRECTION_INHERIT = 0;
1879
1880    /**
1881     * Text direction is using "first strong algorithm". The first strong directional character
1882     * determines the paragraph direction. If there is no strong directional character, the
1883     * paragraph direction is the view's resolved layout direction.
1884     * @hide
1885     */
1886    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1887
1888    /**
1889     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1890     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1891     * If there are neither, the paragraph direction is the view's resolved layout direction.
1892     * @hide
1893     */
1894    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1895
1896    /**
1897     * Text direction is forced to LTR.
1898     * @hide
1899     */
1900    public static final int TEXT_DIRECTION_LTR = 3;
1901
1902    /**
1903     * Text direction is forced to RTL.
1904     * @hide
1905     */
1906    public static final int TEXT_DIRECTION_RTL = 4;
1907
1908    /**
1909     * Text direction is coming from the system Locale.
1910     * @hide
1911     */
1912    public static final int TEXT_DIRECTION_LOCALE = 5;
1913
1914    /**
1915     * Default text direction is inherited
1916     * @hide
1917     */
1918    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1919
1920    /**
1921     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1922     * @hide
1923     */
1924    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1925
1926    /**
1927     * Mask for use with private flags indicating bits used for text direction.
1928     * @hide
1929     */
1930    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1931
1932    /**
1933     * Array of text direction flags for mapping attribute "textDirection" to correct
1934     * flag value.
1935     * @hide
1936     */
1937    private static final int[] TEXT_DIRECTION_FLAGS = {
1938            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1939            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1940            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1941            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1942            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1943            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1944    };
1945
1946    /**
1947     * Indicates whether the view text direction has been resolved.
1948     * @hide
1949     */
1950    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1951
1952    /**
1953     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1954     * @hide
1955     */
1956    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1957
1958    /**
1959     * Mask for use with private flags indicating bits used for resolved text direction.
1960     * @hide
1961     */
1962    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1963
1964    /**
1965     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1966     * @hide
1967     */
1968    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1969            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1970
1971    /*
1972     * Default text alignment. The text alignment of this View is inherited from its parent.
1973     * Use with {@link #setTextAlignment(int)}
1974     * @hide
1975     */
1976    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1977
1978    /**
1979     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1980     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1981     *
1982     * Use with {@link #setTextAlignment(int)}
1983     * @hide
1984     */
1985    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1986
1987    /**
1988     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1989     *
1990     * Use with {@link #setTextAlignment(int)}
1991     * @hide
1992     */
1993    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1994
1995    /**
1996     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1997     *
1998     * Use with {@link #setTextAlignment(int)}
1999     * @hide
2000     */
2001    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2002
2003    /**
2004     * Center the paragraph, e.g. ALIGN_CENTER.
2005     *
2006     * Use with {@link #setTextAlignment(int)}
2007     * @hide
2008     */
2009    public static final int TEXT_ALIGNMENT_CENTER = 4;
2010
2011    /**
2012     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2013     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2014     *
2015     * Use with {@link #setTextAlignment(int)}
2016     * @hide
2017     */
2018    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2019
2020    /**
2021     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2022     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2023     *
2024     * Use with {@link #setTextAlignment(int)}
2025     * @hide
2026     */
2027    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2028
2029    /**
2030     * Default text alignment is inherited
2031     * @hide
2032     */
2033    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2034
2035    /**
2036      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2037      * @hide
2038      */
2039    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2040
2041    /**
2042      * Mask for use with private flags indicating bits used for text alignment.
2043      * @hide
2044      */
2045    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2046
2047    /**
2048     * Array of text direction flags for mapping attribute "textAlignment" to correct
2049     * flag value.
2050     * @hide
2051     */
2052    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2053            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2054            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2055            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2056            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2057            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2058            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2059            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2060    };
2061
2062    /**
2063     * Indicates whether the view text alignment has been resolved.
2064     * @hide
2065     */
2066    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2067
2068    /**
2069     * Bit shift to get the resolved text alignment.
2070     * @hide
2071     */
2072    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2073
2074    /**
2075     * Mask for use with private flags indicating bits used for text alignment.
2076     * @hide
2077     */
2078    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2079
2080    /**
2081     * Indicates whether if the view text alignment has been resolved to gravity
2082     */
2083    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2084            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2085
2086    // Accessiblity constants for mPrivateFlags2
2087
2088    /**
2089     * Shift for the bits in {@link #mPrivateFlags2} related to the
2090     * "importantForAccessibility" attribute.
2091     */
2092    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2093
2094    /**
2095     * Automatically determine whether a view is important for accessibility.
2096     */
2097    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2098
2099    /**
2100     * The view is important for accessibility.
2101     */
2102    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2103
2104    /**
2105     * The view is not important for accessibility.
2106     */
2107    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2108
2109    /**
2110     * The default whether the view is important for accessiblity.
2111     */
2112    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2113
2114    /**
2115     * Mask for obtainig the bits which specify how to determine
2116     * whether a view is important for accessibility.
2117     */
2118    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2119        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2120        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2121
2122    /**
2123     * Flag indicating whether a view has accessibility focus.
2124     */
2125    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2126
2127    /**
2128     * Flag indicating whether a view state for accessibility has changed.
2129     */
2130    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2131
2132    /**
2133     * Flag indicating that view has an animation set on it. This is used to track whether an
2134     * animation is cleared between successive frames, in order to tell the associated
2135     * DisplayList to clear its animation matrix.
2136     */
2137    static final int VIEW_IS_ANIMATING_TRANSFORM = 0x10000000;
2138
2139    /**
2140     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2141     * is used to check whether later changes to the view's transform should invalidate the
2142     * view to force the quickReject test to run again.
2143     */
2144    static final int VIEW_QUICK_REJECTED = 0x20000000;
2145
2146    // Accessiblity constants for mPrivateFlags2
2147
2148    /**
2149     * Shift for the bits in {@link #mPrivateFlags2} related to the
2150     * "accessibilityFocusable" attribute.
2151     */
2152    static final int ACCESSIBILITY_FOCUSABLE_SHIFT = 30;
2153
2154    /**
2155     * The system determines whether the view can take accessibility focus - default (recommended).
2156     * <p>
2157     * Such a view is consideted by the focus search if it is:
2158     * <ul>
2159     * <li>
2160     * Important for accessibility and actionable (clickable, long clickable, focusable)
2161     * </li>
2162     * <li>
2163     * Important for accessibility, not actionable (clickable, long clickable, focusable),
2164     * and does not have an actionable predecessor.
2165     * </li>
2166     * </ul>
2167     * An accessibility srvice can request putting accessibility focus on such a view.
2168     * </p>
2169     *
2170     * @hide
2171     */
2172    public static final int ACCESSIBILITY_FOCUSABLE_AUTO = 0x00000000;
2173
2174    /**
2175     * The view can take accessibility focus.
2176     * <p>
2177     * A view that can take accessibility focus is always considered during focus
2178     * search and an accessibility service can request putting accessibility focus
2179     * on it.
2180     * </p>
2181     *
2182     * @hide
2183     */
2184    public static final int ACCESSIBILITY_FOCUSABLE_YES = 0x00000001;
2185
2186    /**
2187     * The view can not take accessibility focus.
2188     * <p>
2189     * A view that can not take accessibility focus is never considered during focus
2190     * search and an accessibility service can not request putting accessibility focus
2191     * on it.
2192     * </p>
2193     *
2194     * @hide
2195     */
2196    public static final int ACCESSIBILITY_FOCUSABLE_NO = 0x00000002;
2197
2198    /**
2199     * The default whether the view is accessiblity focusable.
2200     */
2201    static final int ACCESSIBILITY_FOCUSABLE_DEFAULT = ACCESSIBILITY_FOCUSABLE_AUTO;
2202
2203    /**
2204     * Mask for obtainig the bits which specifies how to determine
2205     * whether a view is accessibility focusable.
2206     */
2207    static final int ACCESSIBILITY_FOCUSABLE_MASK = (ACCESSIBILITY_FOCUSABLE_AUTO
2208        | ACCESSIBILITY_FOCUSABLE_YES | ACCESSIBILITY_FOCUSABLE_NO)
2209        << ACCESSIBILITY_FOCUSABLE_SHIFT;
2210
2211
2212    /* End of masks for mPrivateFlags2 */
2213
2214    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2215
2216    /**
2217     * Always allow a user to over-scroll this view, provided it is a
2218     * view that can scroll.
2219     *
2220     * @see #getOverScrollMode()
2221     * @see #setOverScrollMode(int)
2222     */
2223    public static final int OVER_SCROLL_ALWAYS = 0;
2224
2225    /**
2226     * Allow a user to over-scroll this view only if the content is large
2227     * enough to meaningfully scroll, provided it is a view that can scroll.
2228     *
2229     * @see #getOverScrollMode()
2230     * @see #setOverScrollMode(int)
2231     */
2232    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2233
2234    /**
2235     * Never allow a user to over-scroll this view.
2236     *
2237     * @see #getOverScrollMode()
2238     * @see #setOverScrollMode(int)
2239     */
2240    public static final int OVER_SCROLL_NEVER = 2;
2241
2242    /**
2243     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2244     * requested the system UI (status bar) to be visible (the default).
2245     *
2246     * @see #setSystemUiVisibility(int)
2247     */
2248    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2249
2250    /**
2251     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2252     * system UI to enter an unobtrusive "low profile" mode.
2253     *
2254     * <p>This is for use in games, book readers, video players, or any other
2255     * "immersive" application where the usual system chrome is deemed too distracting.
2256     *
2257     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2258     *
2259     * @see #setSystemUiVisibility(int)
2260     */
2261    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2262
2263    /**
2264     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2265     * system navigation be temporarily hidden.
2266     *
2267     * <p>This is an even less obtrusive state than that called for by
2268     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2269     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2270     * those to disappear. This is useful (in conjunction with the
2271     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2272     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2273     * window flags) for displaying content using every last pixel on the display.
2274     *
2275     * <p>There is a limitation: because navigation controls are so important, the least user
2276     * interaction will cause them to reappear immediately.  When this happens, both
2277     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2278     * so that both elements reappear at the same time.
2279     *
2280     * @see #setSystemUiVisibility(int)
2281     */
2282    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2283
2284    /**
2285     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2286     * into the normal fullscreen mode so that its content can take over the screen
2287     * while still allowing the user to interact with the application.
2288     *
2289     * <p>This has the same visual effect as
2290     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2291     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2292     * meaning that non-critical screen decorations (such as the status bar) will be
2293     * hidden while the user is in the View's window, focusing the experience on
2294     * that content.  Unlike the window flag, if you are using ActionBar in
2295     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2296     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2297     * hide the action bar.
2298     *
2299     * <p>This approach to going fullscreen is best used over the window flag when
2300     * it is a transient state -- that is, the application does this at certain
2301     * points in its user interaction where it wants to allow the user to focus
2302     * on content, but not as a continuous state.  For situations where the application
2303     * would like to simply stay full screen the entire time (such as a game that
2304     * wants to take over the screen), the
2305     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2306     * is usually a better approach.  The state set here will be removed by the system
2307     * in various situations (such as the user moving to another application) like
2308     * the other system UI states.
2309     *
2310     * <p>When using this flag, the application should provide some easy facility
2311     * for the user to go out of it.  A common example would be in an e-book
2312     * reader, where tapping on the screen brings back whatever screen and UI
2313     * decorations that had been hidden while the user was immersed in reading
2314     * the book.
2315     *
2316     * @see #setSystemUiVisibility(int)
2317     */
2318    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2319
2320    /**
2321     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2322     * flags, we would like a stable view of the content insets given to
2323     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2324     * will always represent the worst case that the application can expect
2325     * as a continuous state.  In the stock Android UI this is the space for
2326     * the system bar, nav bar, and status bar, but not more transient elements
2327     * such as an input method.
2328     *
2329     * The stable layout your UI sees is based on the system UI modes you can
2330     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2331     * then you will get a stable layout for changes of the
2332     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2333     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2334     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2335     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2336     * with a stable layout.  (Note that you should avoid using
2337     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2338     *
2339     * If you have set the window flag {@ WindowManager.LayoutParams#FLAG_FULLSCREEN}
2340     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2341     * then a hidden status bar will be considered a "stable" state for purposes
2342     * here.  This allows your UI to continually hide the status bar, while still
2343     * using the system UI flags to hide the action bar while still retaining
2344     * a stable layout.  Note that changing the window fullscreen flag will never
2345     * provide a stable layout for a clean transition.
2346     *
2347     * <p>If you are using ActionBar in
2348     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2349     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2350     * insets it adds to those given to the application.
2351     */
2352    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2353
2354    /**
2355     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2356     * to be layed out as if it has requested
2357     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2358     * allows it to avoid artifacts when switching in and out of that mode, at
2359     * the expense that some of its user interface may be covered by screen
2360     * decorations when they are shown.  You can perform layout of your inner
2361     * UI elements to account for the navagation system UI through the
2362     * {@link #fitSystemWindows(Rect)} method.
2363     */
2364    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2365
2366    /**
2367     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2368     * to be layed out as if it has requested
2369     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2370     * allows it to avoid artifacts when switching in and out of that mode, at
2371     * the expense that some of its user interface may be covered by screen
2372     * decorations when they are shown.  You can perform layout of your inner
2373     * UI elements to account for non-fullscreen system UI through the
2374     * {@link #fitSystemWindows(Rect)} method.
2375     */
2376    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2377
2378    /**
2379     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2380     */
2381    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2382
2383    /**
2384     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2385     */
2386    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2387
2388    /**
2389     * @hide
2390     *
2391     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2392     * out of the public fields to keep the undefined bits out of the developer's way.
2393     *
2394     * Flag to make the status bar not expandable.  Unless you also
2395     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2396     */
2397    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2398
2399    /**
2400     * @hide
2401     *
2402     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2403     * out of the public fields to keep the undefined bits out of the developer's way.
2404     *
2405     * Flag to hide notification icons and scrolling ticker text.
2406     */
2407    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2408
2409    /**
2410     * @hide
2411     *
2412     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2413     * out of the public fields to keep the undefined bits out of the developer's way.
2414     *
2415     * Flag to disable incoming notification alerts.  This will not block
2416     * icons, but it will block sound, vibrating and other visual or aural notifications.
2417     */
2418    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2419
2420    /**
2421     * @hide
2422     *
2423     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2424     * out of the public fields to keep the undefined bits out of the developer's way.
2425     *
2426     * Flag to hide only the scrolling ticker.  Note that
2427     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2428     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2429     */
2430    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2431
2432    /**
2433     * @hide
2434     *
2435     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2436     * out of the public fields to keep the undefined bits out of the developer's way.
2437     *
2438     * Flag to hide the center system info area.
2439     */
2440    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2441
2442    /**
2443     * @hide
2444     *
2445     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2446     * out of the public fields to keep the undefined bits out of the developer's way.
2447     *
2448     * Flag to hide only the home button.  Don't use this
2449     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2450     */
2451    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2452
2453    /**
2454     * @hide
2455     *
2456     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2457     * out of the public fields to keep the undefined bits out of the developer's way.
2458     *
2459     * Flag to hide only the back button. Don't use this
2460     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2461     */
2462    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2463
2464    /**
2465     * @hide
2466     *
2467     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2468     * out of the public fields to keep the undefined bits out of the developer's way.
2469     *
2470     * Flag to hide only the clock.  You might use this if your activity has
2471     * its own clock making the status bar's clock redundant.
2472     */
2473    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2474
2475    /**
2476     * @hide
2477     *
2478     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2479     * out of the public fields to keep the undefined bits out of the developer's way.
2480     *
2481     * Flag to hide only the recent apps button. Don't use this
2482     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2483     */
2484    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2485
2486    /**
2487     * @hide
2488     */
2489    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2490
2491    /**
2492     * These are the system UI flags that can be cleared by events outside
2493     * of an application.  Currently this is just the ability to tap on the
2494     * screen while hiding the navigation bar to have it return.
2495     * @hide
2496     */
2497    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2498            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2499            | SYSTEM_UI_FLAG_FULLSCREEN;
2500
2501    /**
2502     * Flags that can impact the layout in relation to system UI.
2503     */
2504    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2505            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2506            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2507
2508    /**
2509     * Find views that render the specified text.
2510     *
2511     * @see #findViewsWithText(ArrayList, CharSequence, int)
2512     */
2513    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2514
2515    /**
2516     * Find find views that contain the specified content description.
2517     *
2518     * @see #findViewsWithText(ArrayList, CharSequence, int)
2519     */
2520    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2521
2522    /**
2523     * Find views that contain {@link AccessibilityNodeProvider}. Such
2524     * a View is a root of virtual view hierarchy and may contain the searched
2525     * text. If this flag is set Views with providers are automatically
2526     * added and it is a responsibility of the client to call the APIs of
2527     * the provider to determine whether the virtual tree rooted at this View
2528     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2529     * represeting the virtual views with this text.
2530     *
2531     * @see #findViewsWithText(ArrayList, CharSequence, int)
2532     *
2533     * @hide
2534     */
2535    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2536
2537    /**
2538     * The undefined cursor position.
2539     */
2540    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2541
2542    /**
2543     * Indicates that the screen has changed state and is now off.
2544     *
2545     * @see #onScreenStateChanged(int)
2546     */
2547    public static final int SCREEN_STATE_OFF = 0x0;
2548
2549    /**
2550     * Indicates that the screen has changed state and is now on.
2551     *
2552     * @see #onScreenStateChanged(int)
2553     */
2554    public static final int SCREEN_STATE_ON = 0x1;
2555
2556    /**
2557     * Controls the over-scroll mode for this view.
2558     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2559     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2560     * and {@link #OVER_SCROLL_NEVER}.
2561     */
2562    private int mOverScrollMode;
2563
2564    /**
2565     * The parent this view is attached to.
2566     * {@hide}
2567     *
2568     * @see #getParent()
2569     */
2570    protected ViewParent mParent;
2571
2572    /**
2573     * {@hide}
2574     */
2575    AttachInfo mAttachInfo;
2576
2577    /**
2578     * {@hide}
2579     */
2580    @ViewDebug.ExportedProperty(flagMapping = {
2581        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2582                name = "FORCE_LAYOUT"),
2583        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2584                name = "LAYOUT_REQUIRED"),
2585        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2586            name = "DRAWING_CACHE_INVALID", outputIf = false),
2587        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2588        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2589        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2590        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2591    })
2592    int mPrivateFlags;
2593    int mPrivateFlags2;
2594
2595    /**
2596     * This view's request for the visibility of the status bar.
2597     * @hide
2598     */
2599    @ViewDebug.ExportedProperty(flagMapping = {
2600        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2601                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2602                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2603        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2604                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2605                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2606        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2607                                equals = SYSTEM_UI_FLAG_VISIBLE,
2608                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2609    })
2610    int mSystemUiVisibility;
2611
2612    /**
2613     * Reference count for transient state.
2614     * @see #setHasTransientState(boolean)
2615     */
2616    int mTransientStateCount = 0;
2617
2618    /**
2619     * Count of how many windows this view has been attached to.
2620     */
2621    int mWindowAttachCount;
2622
2623    /**
2624     * The layout parameters associated with this view and used by the parent
2625     * {@link android.view.ViewGroup} to determine how this view should be
2626     * laid out.
2627     * {@hide}
2628     */
2629    protected ViewGroup.LayoutParams mLayoutParams;
2630
2631    /**
2632     * The view flags hold various views states.
2633     * {@hide}
2634     */
2635    @ViewDebug.ExportedProperty
2636    int mViewFlags;
2637
2638    static class TransformationInfo {
2639        /**
2640         * The transform matrix for the View. This transform is calculated internally
2641         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2642         * is used by default. Do *not* use this variable directly; instead call
2643         * getMatrix(), which will automatically recalculate the matrix if necessary
2644         * to get the correct matrix based on the latest rotation and scale properties.
2645         */
2646        private final Matrix mMatrix = new Matrix();
2647
2648        /**
2649         * The transform matrix for the View. This transform is calculated internally
2650         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2651         * is used by default. Do *not* use this variable directly; instead call
2652         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2653         * to get the correct matrix based on the latest rotation and scale properties.
2654         */
2655        private Matrix mInverseMatrix;
2656
2657        /**
2658         * An internal variable that tracks whether we need to recalculate the
2659         * transform matrix, based on whether the rotation or scaleX/Y properties
2660         * have changed since the matrix was last calculated.
2661         */
2662        boolean mMatrixDirty = false;
2663
2664        /**
2665         * An internal variable that tracks whether we need to recalculate the
2666         * transform matrix, based on whether the rotation or scaleX/Y properties
2667         * have changed since the matrix was last calculated.
2668         */
2669        private boolean mInverseMatrixDirty = true;
2670
2671        /**
2672         * A variable that tracks whether we need to recalculate the
2673         * transform matrix, based on whether the rotation or scaleX/Y properties
2674         * have changed since the matrix was last calculated. This variable
2675         * is only valid after a call to updateMatrix() or to a function that
2676         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2677         */
2678        private boolean mMatrixIsIdentity = true;
2679
2680        /**
2681         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2682         */
2683        private Camera mCamera = null;
2684
2685        /**
2686         * This matrix is used when computing the matrix for 3D rotations.
2687         */
2688        private Matrix matrix3D = null;
2689
2690        /**
2691         * These prev values are used to recalculate a centered pivot point when necessary. The
2692         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2693         * set), so thes values are only used then as well.
2694         */
2695        private int mPrevWidth = -1;
2696        private int mPrevHeight = -1;
2697
2698        /**
2699         * The degrees rotation around the vertical axis through the pivot point.
2700         */
2701        @ViewDebug.ExportedProperty
2702        float mRotationY = 0f;
2703
2704        /**
2705         * The degrees rotation around the horizontal axis through the pivot point.
2706         */
2707        @ViewDebug.ExportedProperty
2708        float mRotationX = 0f;
2709
2710        /**
2711         * The degrees rotation around the pivot point.
2712         */
2713        @ViewDebug.ExportedProperty
2714        float mRotation = 0f;
2715
2716        /**
2717         * The amount of translation of the object away from its left property (post-layout).
2718         */
2719        @ViewDebug.ExportedProperty
2720        float mTranslationX = 0f;
2721
2722        /**
2723         * The amount of translation of the object away from its top property (post-layout).
2724         */
2725        @ViewDebug.ExportedProperty
2726        float mTranslationY = 0f;
2727
2728        /**
2729         * The amount of scale in the x direction around the pivot point. A
2730         * value of 1 means no scaling is applied.
2731         */
2732        @ViewDebug.ExportedProperty
2733        float mScaleX = 1f;
2734
2735        /**
2736         * The amount of scale in the y direction around the pivot point. A
2737         * value of 1 means no scaling is applied.
2738         */
2739        @ViewDebug.ExportedProperty
2740        float mScaleY = 1f;
2741
2742        /**
2743         * The x location of the point around which the view is rotated and scaled.
2744         */
2745        @ViewDebug.ExportedProperty
2746        float mPivotX = 0f;
2747
2748        /**
2749         * The y location of the point around which the view is rotated and scaled.
2750         */
2751        @ViewDebug.ExportedProperty
2752        float mPivotY = 0f;
2753
2754        /**
2755         * The opacity of the View. This is a value from 0 to 1, where 0 means
2756         * completely transparent and 1 means completely opaque.
2757         */
2758        @ViewDebug.ExportedProperty
2759        float mAlpha = 1f;
2760    }
2761
2762    TransformationInfo mTransformationInfo;
2763
2764    private boolean mLastIsOpaque;
2765
2766    /**
2767     * Convenience value to check for float values that are close enough to zero to be considered
2768     * zero.
2769     */
2770    private static final float NONZERO_EPSILON = .001f;
2771
2772    /**
2773     * The distance in pixels from the left edge of this view's parent
2774     * to the left edge of this view.
2775     * {@hide}
2776     */
2777    @ViewDebug.ExportedProperty(category = "layout")
2778    protected int mLeft;
2779    /**
2780     * The distance in pixels from the left edge of this view's parent
2781     * to the right edge of this view.
2782     * {@hide}
2783     */
2784    @ViewDebug.ExportedProperty(category = "layout")
2785    protected int mRight;
2786    /**
2787     * The distance in pixels from the top edge of this view's parent
2788     * to the top edge of this view.
2789     * {@hide}
2790     */
2791    @ViewDebug.ExportedProperty(category = "layout")
2792    protected int mTop;
2793    /**
2794     * The distance in pixels from the top edge of this view's parent
2795     * to the bottom edge of this view.
2796     * {@hide}
2797     */
2798    @ViewDebug.ExportedProperty(category = "layout")
2799    protected int mBottom;
2800
2801    /**
2802     * The offset, in pixels, by which the content of this view is scrolled
2803     * horizontally.
2804     * {@hide}
2805     */
2806    @ViewDebug.ExportedProperty(category = "scrolling")
2807    protected int mScrollX;
2808    /**
2809     * The offset, in pixels, by which the content of this view is scrolled
2810     * vertically.
2811     * {@hide}
2812     */
2813    @ViewDebug.ExportedProperty(category = "scrolling")
2814    protected int mScrollY;
2815
2816    /**
2817     * The left padding in pixels, that is the distance in pixels between the
2818     * left edge of this view and the left edge of its content.
2819     * {@hide}
2820     */
2821    @ViewDebug.ExportedProperty(category = "padding")
2822    protected int mPaddingLeft;
2823    /**
2824     * The right padding in pixels, that is the distance in pixels between the
2825     * right edge of this view and the right edge of its content.
2826     * {@hide}
2827     */
2828    @ViewDebug.ExportedProperty(category = "padding")
2829    protected int mPaddingRight;
2830    /**
2831     * The top padding in pixels, that is the distance in pixels between the
2832     * top edge of this view and the top edge of its content.
2833     * {@hide}
2834     */
2835    @ViewDebug.ExportedProperty(category = "padding")
2836    protected int mPaddingTop;
2837    /**
2838     * The bottom padding in pixels, that is the distance in pixels between the
2839     * bottom edge of this view and the bottom edge of its content.
2840     * {@hide}
2841     */
2842    @ViewDebug.ExportedProperty(category = "padding")
2843    protected int mPaddingBottom;
2844
2845    /**
2846     * The layout insets in pixels, that is the distance in pixels between the
2847     * visible edges of this view its bounds.
2848     */
2849    private Insets mLayoutInsets;
2850
2851    /**
2852     * Briefly describes the view and is primarily used for accessibility support.
2853     */
2854    private CharSequence mContentDescription;
2855
2856    /**
2857     * Cache the paddingRight set by the user to append to the scrollbar's size.
2858     *
2859     * @hide
2860     */
2861    @ViewDebug.ExportedProperty(category = "padding")
2862    protected int mUserPaddingRight;
2863
2864    /**
2865     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2866     *
2867     * @hide
2868     */
2869    @ViewDebug.ExportedProperty(category = "padding")
2870    protected int mUserPaddingBottom;
2871
2872    /**
2873     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2874     *
2875     * @hide
2876     */
2877    @ViewDebug.ExportedProperty(category = "padding")
2878    protected int mUserPaddingLeft;
2879
2880    /**
2881     * Cache if the user padding is relative.
2882     *
2883     */
2884    @ViewDebug.ExportedProperty(category = "padding")
2885    boolean mUserPaddingRelative;
2886
2887    /**
2888     * Cache the paddingStart set by the user to append to the scrollbar's size.
2889     *
2890     */
2891    @ViewDebug.ExportedProperty(category = "padding")
2892    int mUserPaddingStart;
2893
2894    /**
2895     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2896     *
2897     */
2898    @ViewDebug.ExportedProperty(category = "padding")
2899    int mUserPaddingEnd;
2900
2901    /**
2902     * @hide
2903     */
2904    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2905    /**
2906     * @hide
2907     */
2908    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2909
2910    private Drawable mBackground;
2911
2912    private int mBackgroundResource;
2913    private boolean mBackgroundSizeChanged;
2914
2915    static class ListenerInfo {
2916        /**
2917         * Listener used to dispatch focus change events.
2918         * This field should be made private, so it is hidden from the SDK.
2919         * {@hide}
2920         */
2921        protected OnFocusChangeListener mOnFocusChangeListener;
2922
2923        /**
2924         * Listeners for layout change events.
2925         */
2926        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2927
2928        /**
2929         * Listeners for attach events.
2930         */
2931        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2932
2933        /**
2934         * Listener used to dispatch click events.
2935         * This field should be made private, so it is hidden from the SDK.
2936         * {@hide}
2937         */
2938        public OnClickListener mOnClickListener;
2939
2940        /**
2941         * Listener used to dispatch long click events.
2942         * This field should be made private, so it is hidden from the SDK.
2943         * {@hide}
2944         */
2945        protected OnLongClickListener mOnLongClickListener;
2946
2947        /**
2948         * Listener used to build the context menu.
2949         * This field should be made private, so it is hidden from the SDK.
2950         * {@hide}
2951         */
2952        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2953
2954        private OnKeyListener mOnKeyListener;
2955
2956        private OnTouchListener mOnTouchListener;
2957
2958        private OnHoverListener mOnHoverListener;
2959
2960        private OnGenericMotionListener mOnGenericMotionListener;
2961
2962        private OnDragListener mOnDragListener;
2963
2964        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2965    }
2966
2967    ListenerInfo mListenerInfo;
2968
2969    /**
2970     * The application environment this view lives in.
2971     * This field should be made private, so it is hidden from the SDK.
2972     * {@hide}
2973     */
2974    protected Context mContext;
2975
2976    private final Resources mResources;
2977
2978    private ScrollabilityCache mScrollCache;
2979
2980    private int[] mDrawableState = null;
2981
2982    /**
2983     * Set to true when drawing cache is enabled and cannot be created.
2984     *
2985     * @hide
2986     */
2987    public boolean mCachingFailed;
2988
2989    private Bitmap mDrawingCache;
2990    private Bitmap mUnscaledDrawingCache;
2991    private HardwareLayer mHardwareLayer;
2992    DisplayList mDisplayList;
2993
2994    /**
2995     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2996     * the user may specify which view to go to next.
2997     */
2998    private int mNextFocusLeftId = View.NO_ID;
2999
3000    /**
3001     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3002     * the user may specify which view to go to next.
3003     */
3004    private int mNextFocusRightId = View.NO_ID;
3005
3006    /**
3007     * When this view has focus and the next focus is {@link #FOCUS_UP},
3008     * the user may specify which view to go to next.
3009     */
3010    private int mNextFocusUpId = View.NO_ID;
3011
3012    /**
3013     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3014     * the user may specify which view to go to next.
3015     */
3016    private int mNextFocusDownId = View.NO_ID;
3017
3018    /**
3019     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3020     * the user may specify which view to go to next.
3021     */
3022    int mNextFocusForwardId = View.NO_ID;
3023
3024    private CheckForLongPress mPendingCheckForLongPress;
3025    private CheckForTap mPendingCheckForTap = null;
3026    private PerformClick mPerformClick;
3027    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3028
3029    private UnsetPressedState mUnsetPressedState;
3030
3031    /**
3032     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3033     * up event while a long press is invoked as soon as the long press duration is reached, so
3034     * a long press could be performed before the tap is checked, in which case the tap's action
3035     * should not be invoked.
3036     */
3037    private boolean mHasPerformedLongPress;
3038
3039    /**
3040     * The minimum height of the view. We'll try our best to have the height
3041     * of this view to at least this amount.
3042     */
3043    @ViewDebug.ExportedProperty(category = "measurement")
3044    private int mMinHeight;
3045
3046    /**
3047     * The minimum width of the view. We'll try our best to have the width
3048     * of this view to at least this amount.
3049     */
3050    @ViewDebug.ExportedProperty(category = "measurement")
3051    private int mMinWidth;
3052
3053    /**
3054     * The delegate to handle touch events that are physically in this view
3055     * but should be handled by another view.
3056     */
3057    private TouchDelegate mTouchDelegate = null;
3058
3059    /**
3060     * Solid color to use as a background when creating the drawing cache. Enables
3061     * the cache to use 16 bit bitmaps instead of 32 bit.
3062     */
3063    private int mDrawingCacheBackgroundColor = 0;
3064
3065    /**
3066     * Special tree observer used when mAttachInfo is null.
3067     */
3068    private ViewTreeObserver mFloatingTreeObserver;
3069
3070    /**
3071     * Cache the touch slop from the context that created the view.
3072     */
3073    private int mTouchSlop;
3074
3075    /**
3076     * Object that handles automatic animation of view properties.
3077     */
3078    private ViewPropertyAnimator mAnimator = null;
3079
3080    /**
3081     * Flag indicating that a drag can cross window boundaries.  When
3082     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3083     * with this flag set, all visible applications will be able to participate
3084     * in the drag operation and receive the dragged content.
3085     *
3086     * @hide
3087     */
3088    public static final int DRAG_FLAG_GLOBAL = 1;
3089
3090    /**
3091     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3092     */
3093    private float mVerticalScrollFactor;
3094
3095    /**
3096     * Position of the vertical scroll bar.
3097     */
3098    private int mVerticalScrollbarPosition;
3099
3100    /**
3101     * Position the scroll bar at the default position as determined by the system.
3102     */
3103    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3104
3105    /**
3106     * Position the scroll bar along the left edge.
3107     */
3108    public static final int SCROLLBAR_POSITION_LEFT = 1;
3109
3110    /**
3111     * Position the scroll bar along the right edge.
3112     */
3113    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3114
3115    /**
3116     * Indicates that the view does not have a layer.
3117     *
3118     * @see #getLayerType()
3119     * @see #setLayerType(int, android.graphics.Paint)
3120     * @see #LAYER_TYPE_SOFTWARE
3121     * @see #LAYER_TYPE_HARDWARE
3122     */
3123    public static final int LAYER_TYPE_NONE = 0;
3124
3125    /**
3126     * <p>Indicates that the view has a software layer. A software layer is backed
3127     * by a bitmap and causes the view to be rendered using Android's software
3128     * rendering pipeline, even if hardware acceleration is enabled.</p>
3129     *
3130     * <p>Software layers have various usages:</p>
3131     * <p>When the application is not using hardware acceleration, a software layer
3132     * is useful to apply a specific color filter and/or blending mode and/or
3133     * translucency to a view and all its children.</p>
3134     * <p>When the application is using hardware acceleration, a software layer
3135     * is useful to render drawing primitives not supported by the hardware
3136     * accelerated pipeline. It can also be used to cache a complex view tree
3137     * into a texture and reduce the complexity of drawing operations. For instance,
3138     * when animating a complex view tree with a translation, a software layer can
3139     * be used to render the view tree only once.</p>
3140     * <p>Software layers should be avoided when the affected view tree updates
3141     * often. Every update will require to re-render the software layer, which can
3142     * potentially be slow (particularly when hardware acceleration is turned on
3143     * since the layer will have to be uploaded into a hardware texture after every
3144     * update.)</p>
3145     *
3146     * @see #getLayerType()
3147     * @see #setLayerType(int, android.graphics.Paint)
3148     * @see #LAYER_TYPE_NONE
3149     * @see #LAYER_TYPE_HARDWARE
3150     */
3151    public static final int LAYER_TYPE_SOFTWARE = 1;
3152
3153    /**
3154     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3155     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3156     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3157     * rendering pipeline, but only if hardware acceleration is turned on for the
3158     * view hierarchy. When hardware acceleration is turned off, hardware layers
3159     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3160     *
3161     * <p>A hardware layer is useful to apply a specific color filter and/or
3162     * blending mode and/or translucency to a view and all its children.</p>
3163     * <p>A hardware layer can be used to cache a complex view tree into a
3164     * texture and reduce the complexity of drawing operations. For instance,
3165     * when animating a complex view tree with a translation, a hardware layer can
3166     * be used to render the view tree only once.</p>
3167     * <p>A hardware layer can also be used to increase the rendering quality when
3168     * rotation transformations are applied on a view. It can also be used to
3169     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3170     *
3171     * @see #getLayerType()
3172     * @see #setLayerType(int, android.graphics.Paint)
3173     * @see #LAYER_TYPE_NONE
3174     * @see #LAYER_TYPE_SOFTWARE
3175     */
3176    public static final int LAYER_TYPE_HARDWARE = 2;
3177
3178    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3179            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3180            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3181            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3182    })
3183    int mLayerType = LAYER_TYPE_NONE;
3184    Paint mLayerPaint;
3185    Rect mLocalDirtyRect;
3186
3187    /**
3188     * Set to true when the view is sending hover accessibility events because it
3189     * is the innermost hovered view.
3190     */
3191    private boolean mSendingHoverAccessibilityEvents;
3192
3193    /**
3194     * Simple constructor to use when creating a view from code.
3195     *
3196     * @param context The Context the view is running in, through which it can
3197     *        access the current theme, resources, etc.
3198     */
3199    public View(Context context) {
3200        mContext = context;
3201        mResources = context != null ? context.getResources() : null;
3202        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3203        // Set layout and text direction defaults
3204        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3205                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3206                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3207                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT) |
3208                (ACCESSIBILITY_FOCUSABLE_DEFAULT << ACCESSIBILITY_FOCUSABLE_SHIFT);
3209        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3210        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3211        mUserPaddingStart = -1;
3212        mUserPaddingEnd = -1;
3213        mUserPaddingRelative = false;
3214    }
3215
3216    /**
3217     * Delegate for injecting accessiblity functionality.
3218     */
3219    AccessibilityDelegate mAccessibilityDelegate;
3220
3221    /**
3222     * Consistency verifier for debugging purposes.
3223     * @hide
3224     */
3225    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3226            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3227                    new InputEventConsistencyVerifier(this, 0) : null;
3228
3229    /**
3230     * Constructor that is called when inflating a view from XML. This is called
3231     * when a view is being constructed from an XML file, supplying attributes
3232     * that were specified in the XML file. This version uses a default style of
3233     * 0, so the only attribute values applied are those in the Context's Theme
3234     * and the given AttributeSet.
3235     *
3236     * <p>
3237     * The method onFinishInflate() will be called after all children have been
3238     * added.
3239     *
3240     * @param context The Context the view is running in, through which it can
3241     *        access the current theme, resources, etc.
3242     * @param attrs The attributes of the XML tag that is inflating the view.
3243     * @see #View(Context, AttributeSet, int)
3244     */
3245    public View(Context context, AttributeSet attrs) {
3246        this(context, attrs, 0);
3247    }
3248
3249    /**
3250     * Perform inflation from XML and apply a class-specific base style. This
3251     * constructor of View allows subclasses to use their own base style when
3252     * they are inflating. For example, a Button class's constructor would call
3253     * this version of the super class constructor and supply
3254     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3255     * the theme's button style to modify all of the base view attributes (in
3256     * particular its background) as well as the Button class's attributes.
3257     *
3258     * @param context The Context the view is running in, through which it can
3259     *        access the current theme, resources, etc.
3260     * @param attrs The attributes of the XML tag that is inflating the view.
3261     * @param defStyle The default style to apply to this view. If 0, no style
3262     *        will be applied (beyond what is included in the theme). This may
3263     *        either be an attribute resource, whose value will be retrieved
3264     *        from the current theme, or an explicit style resource.
3265     * @see #View(Context, AttributeSet)
3266     */
3267    public View(Context context, AttributeSet attrs, int defStyle) {
3268        this(context);
3269
3270        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3271                defStyle, 0);
3272
3273        Drawable background = null;
3274
3275        int leftPadding = -1;
3276        int topPadding = -1;
3277        int rightPadding = -1;
3278        int bottomPadding = -1;
3279        int startPadding = -1;
3280        int endPadding = -1;
3281
3282        int padding = -1;
3283
3284        int viewFlagValues = 0;
3285        int viewFlagMasks = 0;
3286
3287        boolean setScrollContainer = false;
3288
3289        int x = 0;
3290        int y = 0;
3291
3292        float tx = 0;
3293        float ty = 0;
3294        float rotation = 0;
3295        float rotationX = 0;
3296        float rotationY = 0;
3297        float sx = 1f;
3298        float sy = 1f;
3299        boolean transformSet = false;
3300
3301        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3302
3303        int overScrollMode = mOverScrollMode;
3304        final int N = a.getIndexCount();
3305        for (int i = 0; i < N; i++) {
3306            int attr = a.getIndex(i);
3307            switch (attr) {
3308                case com.android.internal.R.styleable.View_background:
3309                    background = a.getDrawable(attr);
3310                    break;
3311                case com.android.internal.R.styleable.View_padding:
3312                    padding = a.getDimensionPixelSize(attr, -1);
3313                    break;
3314                 case com.android.internal.R.styleable.View_paddingLeft:
3315                    leftPadding = a.getDimensionPixelSize(attr, -1);
3316                    break;
3317                case com.android.internal.R.styleable.View_paddingTop:
3318                    topPadding = a.getDimensionPixelSize(attr, -1);
3319                    break;
3320                case com.android.internal.R.styleable.View_paddingRight:
3321                    rightPadding = a.getDimensionPixelSize(attr, -1);
3322                    break;
3323                case com.android.internal.R.styleable.View_paddingBottom:
3324                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3325                    break;
3326                case com.android.internal.R.styleable.View_paddingStart:
3327                    startPadding = a.getDimensionPixelSize(attr, -1);
3328                    break;
3329                case com.android.internal.R.styleable.View_paddingEnd:
3330                    endPadding = a.getDimensionPixelSize(attr, -1);
3331                    break;
3332                case com.android.internal.R.styleable.View_scrollX:
3333                    x = a.getDimensionPixelOffset(attr, 0);
3334                    break;
3335                case com.android.internal.R.styleable.View_scrollY:
3336                    y = a.getDimensionPixelOffset(attr, 0);
3337                    break;
3338                case com.android.internal.R.styleable.View_alpha:
3339                    setAlpha(a.getFloat(attr, 1f));
3340                    break;
3341                case com.android.internal.R.styleable.View_transformPivotX:
3342                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3343                    break;
3344                case com.android.internal.R.styleable.View_transformPivotY:
3345                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3346                    break;
3347                case com.android.internal.R.styleable.View_translationX:
3348                    tx = a.getDimensionPixelOffset(attr, 0);
3349                    transformSet = true;
3350                    break;
3351                case com.android.internal.R.styleable.View_translationY:
3352                    ty = a.getDimensionPixelOffset(attr, 0);
3353                    transformSet = true;
3354                    break;
3355                case com.android.internal.R.styleable.View_rotation:
3356                    rotation = a.getFloat(attr, 0);
3357                    transformSet = true;
3358                    break;
3359                case com.android.internal.R.styleable.View_rotationX:
3360                    rotationX = a.getFloat(attr, 0);
3361                    transformSet = true;
3362                    break;
3363                case com.android.internal.R.styleable.View_rotationY:
3364                    rotationY = a.getFloat(attr, 0);
3365                    transformSet = true;
3366                    break;
3367                case com.android.internal.R.styleable.View_scaleX:
3368                    sx = a.getFloat(attr, 1f);
3369                    transformSet = true;
3370                    break;
3371                case com.android.internal.R.styleable.View_scaleY:
3372                    sy = a.getFloat(attr, 1f);
3373                    transformSet = true;
3374                    break;
3375                case com.android.internal.R.styleable.View_id:
3376                    mID = a.getResourceId(attr, NO_ID);
3377                    break;
3378                case com.android.internal.R.styleable.View_tag:
3379                    mTag = a.getText(attr);
3380                    break;
3381                case com.android.internal.R.styleable.View_fitsSystemWindows:
3382                    if (a.getBoolean(attr, false)) {
3383                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3384                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3385                    }
3386                    break;
3387                case com.android.internal.R.styleable.View_focusable:
3388                    if (a.getBoolean(attr, false)) {
3389                        viewFlagValues |= FOCUSABLE;
3390                        viewFlagMasks |= FOCUSABLE_MASK;
3391                    }
3392                    break;
3393                case com.android.internal.R.styleable.View_focusableInTouchMode:
3394                    if (a.getBoolean(attr, false)) {
3395                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3396                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3397                    }
3398                    break;
3399                case com.android.internal.R.styleable.View_clickable:
3400                    if (a.getBoolean(attr, false)) {
3401                        viewFlagValues |= CLICKABLE;
3402                        viewFlagMasks |= CLICKABLE;
3403                    }
3404                    break;
3405                case com.android.internal.R.styleable.View_longClickable:
3406                    if (a.getBoolean(attr, false)) {
3407                        viewFlagValues |= LONG_CLICKABLE;
3408                        viewFlagMasks |= LONG_CLICKABLE;
3409                    }
3410                    break;
3411                case com.android.internal.R.styleable.View_saveEnabled:
3412                    if (!a.getBoolean(attr, true)) {
3413                        viewFlagValues |= SAVE_DISABLED;
3414                        viewFlagMasks |= SAVE_DISABLED_MASK;
3415                    }
3416                    break;
3417                case com.android.internal.R.styleable.View_duplicateParentState:
3418                    if (a.getBoolean(attr, false)) {
3419                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3420                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3421                    }
3422                    break;
3423                case com.android.internal.R.styleable.View_visibility:
3424                    final int visibility = a.getInt(attr, 0);
3425                    if (visibility != 0) {
3426                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3427                        viewFlagMasks |= VISIBILITY_MASK;
3428                    }
3429                    break;
3430                case com.android.internal.R.styleable.View_layoutDirection:
3431                    // Clear any layout direction flags (included resolved bits) already set
3432                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3433                    // Set the layout direction flags depending on the value of the attribute
3434                    final int layoutDirection = a.getInt(attr, -1);
3435                    final int value = (layoutDirection != -1) ?
3436                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3437                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3438                    break;
3439                case com.android.internal.R.styleable.View_drawingCacheQuality:
3440                    final int cacheQuality = a.getInt(attr, 0);
3441                    if (cacheQuality != 0) {
3442                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3443                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3444                    }
3445                    break;
3446                case com.android.internal.R.styleable.View_contentDescription:
3447                    mContentDescription = a.getString(attr);
3448                    break;
3449                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3450                    if (!a.getBoolean(attr, true)) {
3451                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3452                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3453                    }
3454                    break;
3455                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3456                    if (!a.getBoolean(attr, true)) {
3457                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3458                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3459                    }
3460                    break;
3461                case R.styleable.View_scrollbars:
3462                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3463                    if (scrollbars != SCROLLBARS_NONE) {
3464                        viewFlagValues |= scrollbars;
3465                        viewFlagMasks |= SCROLLBARS_MASK;
3466                        initializeScrollbars(a);
3467                    }
3468                    break;
3469                //noinspection deprecation
3470                case R.styleable.View_fadingEdge:
3471                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3472                        // Ignore the attribute starting with ICS
3473                        break;
3474                    }
3475                    // With builds < ICS, fall through and apply fading edges
3476                case R.styleable.View_requiresFadingEdge:
3477                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3478                    if (fadingEdge != FADING_EDGE_NONE) {
3479                        viewFlagValues |= fadingEdge;
3480                        viewFlagMasks |= FADING_EDGE_MASK;
3481                        initializeFadingEdge(a);
3482                    }
3483                    break;
3484                case R.styleable.View_scrollbarStyle:
3485                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3486                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3487                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3488                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3489                    }
3490                    break;
3491                case R.styleable.View_isScrollContainer:
3492                    setScrollContainer = true;
3493                    if (a.getBoolean(attr, false)) {
3494                        setScrollContainer(true);
3495                    }
3496                    break;
3497                case com.android.internal.R.styleable.View_keepScreenOn:
3498                    if (a.getBoolean(attr, false)) {
3499                        viewFlagValues |= KEEP_SCREEN_ON;
3500                        viewFlagMasks |= KEEP_SCREEN_ON;
3501                    }
3502                    break;
3503                case R.styleable.View_filterTouchesWhenObscured:
3504                    if (a.getBoolean(attr, false)) {
3505                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3506                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3507                    }
3508                    break;
3509                case R.styleable.View_nextFocusLeft:
3510                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3511                    break;
3512                case R.styleable.View_nextFocusRight:
3513                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3514                    break;
3515                case R.styleable.View_nextFocusUp:
3516                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3517                    break;
3518                case R.styleable.View_nextFocusDown:
3519                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3520                    break;
3521                case R.styleable.View_nextFocusForward:
3522                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3523                    break;
3524                case R.styleable.View_minWidth:
3525                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3526                    break;
3527                case R.styleable.View_minHeight:
3528                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3529                    break;
3530                case R.styleable.View_onClick:
3531                    if (context.isRestricted()) {
3532                        throw new IllegalStateException("The android:onClick attribute cannot "
3533                                + "be used within a restricted context");
3534                    }
3535
3536                    final String handlerName = a.getString(attr);
3537                    if (handlerName != null) {
3538                        setOnClickListener(new OnClickListener() {
3539                            private Method mHandler;
3540
3541                            public void onClick(View v) {
3542                                if (mHandler == null) {
3543                                    try {
3544                                        mHandler = getContext().getClass().getMethod(handlerName,
3545                                                View.class);
3546                                    } catch (NoSuchMethodException e) {
3547                                        int id = getId();
3548                                        String idText = id == NO_ID ? "" : " with id '"
3549                                                + getContext().getResources().getResourceEntryName(
3550                                                    id) + "'";
3551                                        throw new IllegalStateException("Could not find a method " +
3552                                                handlerName + "(View) in the activity "
3553                                                + getContext().getClass() + " for onClick handler"
3554                                                + " on view " + View.this.getClass() + idText, e);
3555                                    }
3556                                }
3557
3558                                try {
3559                                    mHandler.invoke(getContext(), View.this);
3560                                } catch (IllegalAccessException e) {
3561                                    throw new IllegalStateException("Could not execute non "
3562                                            + "public method of the activity", e);
3563                                } catch (InvocationTargetException e) {
3564                                    throw new IllegalStateException("Could not execute "
3565                                            + "method of the activity", e);
3566                                }
3567                            }
3568                        });
3569                    }
3570                    break;
3571                case R.styleable.View_overScrollMode:
3572                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3573                    break;
3574                case R.styleable.View_verticalScrollbarPosition:
3575                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3576                    break;
3577                case R.styleable.View_layerType:
3578                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3579                    break;
3580                case R.styleable.View_textDirection:
3581                    // Clear any text direction flag already set
3582                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3583                    // Set the text direction flags depending on the value of the attribute
3584                    final int textDirection = a.getInt(attr, -1);
3585                    if (textDirection != -1) {
3586                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3587                    }
3588                    break;
3589                case R.styleable.View_textAlignment:
3590                    // Clear any text alignment flag already set
3591                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3592                    // Set the text alignment flag depending on the value of the attribute
3593                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3594                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3595                    break;
3596                case R.styleable.View_importantForAccessibility:
3597                    setImportantForAccessibility(a.getInt(attr,
3598                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3599            }
3600        }
3601
3602        a.recycle();
3603
3604        setOverScrollMode(overScrollMode);
3605
3606        if (background != null) {
3607            setBackground(background);
3608        }
3609
3610        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3611        // layout direction). Those cached values will be used later during padding resolution.
3612        mUserPaddingStart = startPadding;
3613        mUserPaddingEnd = endPadding;
3614
3615        updateUserPaddingRelative();
3616
3617        if (padding >= 0) {
3618            leftPadding = padding;
3619            topPadding = padding;
3620            rightPadding = padding;
3621            bottomPadding = padding;
3622        }
3623
3624        // If the user specified the padding (either with android:padding or
3625        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3626        // use the default padding or the padding from the background drawable
3627        // (stored at this point in mPadding*)
3628        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3629                topPadding >= 0 ? topPadding : mPaddingTop,
3630                rightPadding >= 0 ? rightPadding : mPaddingRight,
3631                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3632
3633        if (viewFlagMasks != 0) {
3634            setFlags(viewFlagValues, viewFlagMasks);
3635        }
3636
3637        // Needs to be called after mViewFlags is set
3638        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3639            recomputePadding();
3640        }
3641
3642        if (x != 0 || y != 0) {
3643            scrollTo(x, y);
3644        }
3645
3646        if (transformSet) {
3647            setTranslationX(tx);
3648            setTranslationY(ty);
3649            setRotation(rotation);
3650            setRotationX(rotationX);
3651            setRotationY(rotationY);
3652            setScaleX(sx);
3653            setScaleY(sy);
3654        }
3655
3656        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3657            setScrollContainer(true);
3658        }
3659
3660        computeOpaqueFlags();
3661    }
3662
3663    private void updateUserPaddingRelative() {
3664        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3665    }
3666
3667    /**
3668     * Non-public constructor for use in testing
3669     */
3670    View() {
3671        mResources = null;
3672    }
3673
3674    /**
3675     * <p>
3676     * Initializes the fading edges from a given set of styled attributes. This
3677     * method should be called by subclasses that need fading edges and when an
3678     * instance of these subclasses is created programmatically rather than
3679     * being inflated from XML. This method is automatically called when the XML
3680     * is inflated.
3681     * </p>
3682     *
3683     * @param a the styled attributes set to initialize the fading edges from
3684     */
3685    protected void initializeFadingEdge(TypedArray a) {
3686        initScrollCache();
3687
3688        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3689                R.styleable.View_fadingEdgeLength,
3690                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3691    }
3692
3693    /**
3694     * Returns the size of the vertical faded edges used to indicate that more
3695     * content in this view is visible.
3696     *
3697     * @return The size in pixels of the vertical faded edge or 0 if vertical
3698     *         faded edges are not enabled for this view.
3699     * @attr ref android.R.styleable#View_fadingEdgeLength
3700     */
3701    public int getVerticalFadingEdgeLength() {
3702        if (isVerticalFadingEdgeEnabled()) {
3703            ScrollabilityCache cache = mScrollCache;
3704            if (cache != null) {
3705                return cache.fadingEdgeLength;
3706            }
3707        }
3708        return 0;
3709    }
3710
3711    /**
3712     * Set the size of the faded edge used to indicate that more content in this
3713     * view is available.  Will not change whether the fading edge is enabled; use
3714     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3715     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3716     * for the vertical or horizontal fading edges.
3717     *
3718     * @param length The size in pixels of the faded edge used to indicate that more
3719     *        content in this view is visible.
3720     */
3721    public void setFadingEdgeLength(int length) {
3722        initScrollCache();
3723        mScrollCache.fadingEdgeLength = length;
3724    }
3725
3726    /**
3727     * Returns the size of the horizontal faded edges used to indicate that more
3728     * content in this view is visible.
3729     *
3730     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3731     *         faded edges are not enabled for this view.
3732     * @attr ref android.R.styleable#View_fadingEdgeLength
3733     */
3734    public int getHorizontalFadingEdgeLength() {
3735        if (isHorizontalFadingEdgeEnabled()) {
3736            ScrollabilityCache cache = mScrollCache;
3737            if (cache != null) {
3738                return cache.fadingEdgeLength;
3739            }
3740        }
3741        return 0;
3742    }
3743
3744    /**
3745     * Returns the width of the vertical scrollbar.
3746     *
3747     * @return The width in pixels of the vertical scrollbar or 0 if there
3748     *         is no vertical scrollbar.
3749     */
3750    public int getVerticalScrollbarWidth() {
3751        ScrollabilityCache cache = mScrollCache;
3752        if (cache != null) {
3753            ScrollBarDrawable scrollBar = cache.scrollBar;
3754            if (scrollBar != null) {
3755                int size = scrollBar.getSize(true);
3756                if (size <= 0) {
3757                    size = cache.scrollBarSize;
3758                }
3759                return size;
3760            }
3761            return 0;
3762        }
3763        return 0;
3764    }
3765
3766    /**
3767     * Returns the height of the horizontal scrollbar.
3768     *
3769     * @return The height in pixels of the horizontal scrollbar or 0 if
3770     *         there is no horizontal scrollbar.
3771     */
3772    protected int getHorizontalScrollbarHeight() {
3773        ScrollabilityCache cache = mScrollCache;
3774        if (cache != null) {
3775            ScrollBarDrawable scrollBar = cache.scrollBar;
3776            if (scrollBar != null) {
3777                int size = scrollBar.getSize(false);
3778                if (size <= 0) {
3779                    size = cache.scrollBarSize;
3780                }
3781                return size;
3782            }
3783            return 0;
3784        }
3785        return 0;
3786    }
3787
3788    /**
3789     * <p>
3790     * Initializes the scrollbars from a given set of styled attributes. This
3791     * method should be called by subclasses that need scrollbars and when an
3792     * instance of these subclasses is created programmatically rather than
3793     * being inflated from XML. This method is automatically called when the XML
3794     * is inflated.
3795     * </p>
3796     *
3797     * @param a the styled attributes set to initialize the scrollbars from
3798     */
3799    protected void initializeScrollbars(TypedArray a) {
3800        initScrollCache();
3801
3802        final ScrollabilityCache scrollabilityCache = mScrollCache;
3803
3804        if (scrollabilityCache.scrollBar == null) {
3805            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3806        }
3807
3808        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3809
3810        if (!fadeScrollbars) {
3811            scrollabilityCache.state = ScrollabilityCache.ON;
3812        }
3813        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3814
3815
3816        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3817                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3818                        .getScrollBarFadeDuration());
3819        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3820                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3821                ViewConfiguration.getScrollDefaultDelay());
3822
3823
3824        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3825                com.android.internal.R.styleable.View_scrollbarSize,
3826                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3827
3828        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3829        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3830
3831        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3832        if (thumb != null) {
3833            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3834        }
3835
3836        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3837                false);
3838        if (alwaysDraw) {
3839            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3840        }
3841
3842        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3843        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3844
3845        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3846        if (thumb != null) {
3847            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3848        }
3849
3850        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3851                false);
3852        if (alwaysDraw) {
3853            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3854        }
3855
3856        // Re-apply user/background padding so that scrollbar(s) get added
3857        resolvePadding();
3858    }
3859
3860    /**
3861     * <p>
3862     * Initalizes the scrollability cache if necessary.
3863     * </p>
3864     */
3865    private void initScrollCache() {
3866        if (mScrollCache == null) {
3867            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3868        }
3869    }
3870
3871    private ScrollabilityCache getScrollCache() {
3872        initScrollCache();
3873        return mScrollCache;
3874    }
3875
3876    /**
3877     * Set the position of the vertical scroll bar. Should be one of
3878     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3879     * {@link #SCROLLBAR_POSITION_RIGHT}.
3880     *
3881     * @param position Where the vertical scroll bar should be positioned.
3882     */
3883    public void setVerticalScrollbarPosition(int position) {
3884        if (mVerticalScrollbarPosition != position) {
3885            mVerticalScrollbarPosition = position;
3886            computeOpaqueFlags();
3887            resolvePadding();
3888        }
3889    }
3890
3891    /**
3892     * @return The position where the vertical scroll bar will show, if applicable.
3893     * @see #setVerticalScrollbarPosition(int)
3894     */
3895    public int getVerticalScrollbarPosition() {
3896        return mVerticalScrollbarPosition;
3897    }
3898
3899    ListenerInfo getListenerInfo() {
3900        if (mListenerInfo != null) {
3901            return mListenerInfo;
3902        }
3903        mListenerInfo = new ListenerInfo();
3904        return mListenerInfo;
3905    }
3906
3907    /**
3908     * Register a callback to be invoked when focus of this view changed.
3909     *
3910     * @param l The callback that will run.
3911     */
3912    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3913        getListenerInfo().mOnFocusChangeListener = l;
3914    }
3915
3916    /**
3917     * Add a listener that will be called when the bounds of the view change due to
3918     * layout processing.
3919     *
3920     * @param listener The listener that will be called when layout bounds change.
3921     */
3922    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3923        ListenerInfo li = getListenerInfo();
3924        if (li.mOnLayoutChangeListeners == null) {
3925            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3926        }
3927        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3928            li.mOnLayoutChangeListeners.add(listener);
3929        }
3930    }
3931
3932    /**
3933     * Remove a listener for layout changes.
3934     *
3935     * @param listener The listener for layout bounds change.
3936     */
3937    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3938        ListenerInfo li = mListenerInfo;
3939        if (li == null || li.mOnLayoutChangeListeners == null) {
3940            return;
3941        }
3942        li.mOnLayoutChangeListeners.remove(listener);
3943    }
3944
3945    /**
3946     * Add a listener for attach state changes.
3947     *
3948     * This listener will be called whenever this view is attached or detached
3949     * from a window. Remove the listener using
3950     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3951     *
3952     * @param listener Listener to attach
3953     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3954     */
3955    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3956        ListenerInfo li = getListenerInfo();
3957        if (li.mOnAttachStateChangeListeners == null) {
3958            li.mOnAttachStateChangeListeners
3959                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3960        }
3961        li.mOnAttachStateChangeListeners.add(listener);
3962    }
3963
3964    /**
3965     * Remove a listener for attach state changes. The listener will receive no further
3966     * notification of window attach/detach events.
3967     *
3968     * @param listener Listener to remove
3969     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3970     */
3971    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3972        ListenerInfo li = mListenerInfo;
3973        if (li == null || li.mOnAttachStateChangeListeners == null) {
3974            return;
3975        }
3976        li.mOnAttachStateChangeListeners.remove(listener);
3977    }
3978
3979    /**
3980     * Returns the focus-change callback registered for this view.
3981     *
3982     * @return The callback, or null if one is not registered.
3983     */
3984    public OnFocusChangeListener getOnFocusChangeListener() {
3985        ListenerInfo li = mListenerInfo;
3986        return li != null ? li.mOnFocusChangeListener : null;
3987    }
3988
3989    /**
3990     * Register a callback to be invoked when this view is clicked. If this view is not
3991     * clickable, it becomes clickable.
3992     *
3993     * @param l The callback that will run
3994     *
3995     * @see #setClickable(boolean)
3996     */
3997    public void setOnClickListener(OnClickListener l) {
3998        if (!isClickable()) {
3999            setClickable(true);
4000        }
4001        getListenerInfo().mOnClickListener = l;
4002    }
4003
4004    /**
4005     * Return whether this view has an attached OnClickListener.  Returns
4006     * true if there is a listener, false if there is none.
4007     */
4008    public boolean hasOnClickListeners() {
4009        ListenerInfo li = mListenerInfo;
4010        return (li != null && li.mOnClickListener != null);
4011    }
4012
4013    /**
4014     * Register a callback to be invoked when this view is clicked and held. If this view is not
4015     * long clickable, it becomes long clickable.
4016     *
4017     * @param l The callback that will run
4018     *
4019     * @see #setLongClickable(boolean)
4020     */
4021    public void setOnLongClickListener(OnLongClickListener l) {
4022        if (!isLongClickable()) {
4023            setLongClickable(true);
4024        }
4025        getListenerInfo().mOnLongClickListener = l;
4026    }
4027
4028    /**
4029     * Register a callback to be invoked when the context menu for this view is
4030     * being built. If this view is not long clickable, it becomes long clickable.
4031     *
4032     * @param l The callback that will run
4033     *
4034     */
4035    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4036        if (!isLongClickable()) {
4037            setLongClickable(true);
4038        }
4039        getListenerInfo().mOnCreateContextMenuListener = l;
4040    }
4041
4042    /**
4043     * Call this view's OnClickListener, if it is defined.  Performs all normal
4044     * actions associated with clicking: reporting accessibility event, playing
4045     * a sound, etc.
4046     *
4047     * @return True there was an assigned OnClickListener that was called, false
4048     *         otherwise is returned.
4049     */
4050    public boolean performClick() {
4051        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4052
4053        ListenerInfo li = mListenerInfo;
4054        if (li != null && li.mOnClickListener != null) {
4055            playSoundEffect(SoundEffectConstants.CLICK);
4056            li.mOnClickListener.onClick(this);
4057            return true;
4058        }
4059
4060        return false;
4061    }
4062
4063    /**
4064     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4065     * this only calls the listener, and does not do any associated clicking
4066     * actions like reporting an accessibility event.
4067     *
4068     * @return True there was an assigned OnClickListener that was called, false
4069     *         otherwise is returned.
4070     */
4071    public boolean callOnClick() {
4072        ListenerInfo li = mListenerInfo;
4073        if (li != null && li.mOnClickListener != null) {
4074            li.mOnClickListener.onClick(this);
4075            return true;
4076        }
4077        return false;
4078    }
4079
4080    /**
4081     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4082     * OnLongClickListener did not consume the event.
4083     *
4084     * @return True if one of the above receivers consumed the event, false otherwise.
4085     */
4086    public boolean performLongClick() {
4087        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4088
4089        boolean handled = false;
4090        ListenerInfo li = mListenerInfo;
4091        if (li != null && li.mOnLongClickListener != null) {
4092            handled = li.mOnLongClickListener.onLongClick(View.this);
4093        }
4094        if (!handled) {
4095            handled = showContextMenu();
4096        }
4097        if (handled) {
4098            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4099        }
4100        return handled;
4101    }
4102
4103    /**
4104     * Performs button-related actions during a touch down event.
4105     *
4106     * @param event The event.
4107     * @return True if the down was consumed.
4108     *
4109     * @hide
4110     */
4111    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4112        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4113            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4114                return true;
4115            }
4116        }
4117        return false;
4118    }
4119
4120    /**
4121     * Bring up the context menu for this view.
4122     *
4123     * @return Whether a context menu was displayed.
4124     */
4125    public boolean showContextMenu() {
4126        return getParent().showContextMenuForChild(this);
4127    }
4128
4129    /**
4130     * Bring up the context menu for this view, referring to the item under the specified point.
4131     *
4132     * @param x The referenced x coordinate.
4133     * @param y The referenced y coordinate.
4134     * @param metaState The keyboard modifiers that were pressed.
4135     * @return Whether a context menu was displayed.
4136     *
4137     * @hide
4138     */
4139    public boolean showContextMenu(float x, float y, int metaState) {
4140        return showContextMenu();
4141    }
4142
4143    /**
4144     * Start an action mode.
4145     *
4146     * @param callback Callback that will control the lifecycle of the action mode
4147     * @return The new action mode if it is started, null otherwise
4148     *
4149     * @see ActionMode
4150     */
4151    public ActionMode startActionMode(ActionMode.Callback callback) {
4152        ViewParent parent = getParent();
4153        if (parent == null) return null;
4154        return parent.startActionModeForChild(this, callback);
4155    }
4156
4157    /**
4158     * Register a callback to be invoked when a hardware key is pressed in this view.
4159     * Key presses in software input methods will generally not trigger the methods of
4160     * this listener.
4161     * @param l the key listener to attach to this view
4162     */
4163    public void setOnKeyListener(OnKeyListener l) {
4164        getListenerInfo().mOnKeyListener = l;
4165    }
4166
4167    /**
4168     * Register a callback to be invoked when a touch event is sent to this view.
4169     * @param l the touch listener to attach to this view
4170     */
4171    public void setOnTouchListener(OnTouchListener l) {
4172        getListenerInfo().mOnTouchListener = l;
4173    }
4174
4175    /**
4176     * Register a callback to be invoked when a generic motion event is sent to this view.
4177     * @param l the generic motion listener to attach to this view
4178     */
4179    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4180        getListenerInfo().mOnGenericMotionListener = l;
4181    }
4182
4183    /**
4184     * Register a callback to be invoked when a hover event is sent to this view.
4185     * @param l the hover listener to attach to this view
4186     */
4187    public void setOnHoverListener(OnHoverListener l) {
4188        getListenerInfo().mOnHoverListener = l;
4189    }
4190
4191    /**
4192     * Register a drag event listener callback object for this View. The parameter is
4193     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4194     * View, the system calls the
4195     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4196     * @param l An implementation of {@link android.view.View.OnDragListener}.
4197     */
4198    public void setOnDragListener(OnDragListener l) {
4199        getListenerInfo().mOnDragListener = l;
4200    }
4201
4202    /**
4203     * Give this view focus. This will cause
4204     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4205     *
4206     * Note: this does not check whether this {@link View} should get focus, it just
4207     * gives it focus no matter what.  It should only be called internally by framework
4208     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4209     *
4210     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4211     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4212     *        focus moved when requestFocus() is called. It may not always
4213     *        apply, in which case use the default View.FOCUS_DOWN.
4214     * @param previouslyFocusedRect The rectangle of the view that had focus
4215     *        prior in this View's coordinate system.
4216     */
4217    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4218        if (DBG) {
4219            System.out.println(this + " requestFocus()");
4220        }
4221
4222        if ((mPrivateFlags & FOCUSED) == 0) {
4223            mPrivateFlags |= FOCUSED;
4224
4225            if (mParent != null) {
4226                mParent.requestChildFocus(this, this);
4227            }
4228
4229            onFocusChanged(true, direction, previouslyFocusedRect);
4230            refreshDrawableState();
4231
4232            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4233                notifyAccessibilityStateChanged();
4234            }
4235        }
4236    }
4237
4238    /**
4239     * Request that a rectangle of this view be visible on the screen,
4240     * scrolling if necessary just enough.
4241     *
4242     * <p>A View should call this if it maintains some notion of which part
4243     * of its content is interesting.  For example, a text editing view
4244     * should call this when its cursor moves.
4245     *
4246     * @param rectangle The rectangle.
4247     * @return Whether any parent scrolled.
4248     */
4249    public boolean requestRectangleOnScreen(Rect rectangle) {
4250        return requestRectangleOnScreen(rectangle, false);
4251    }
4252
4253    /**
4254     * Request that a rectangle of this view be visible on the screen,
4255     * scrolling if necessary just enough.
4256     *
4257     * <p>A View should call this if it maintains some notion of which part
4258     * of its content is interesting.  For example, a text editing view
4259     * should call this when its cursor moves.
4260     *
4261     * <p>When <code>immediate</code> is set to true, scrolling will not be
4262     * animated.
4263     *
4264     * @param rectangle The rectangle.
4265     * @param immediate True to forbid animated scrolling, false otherwise
4266     * @return Whether any parent scrolled.
4267     */
4268    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4269        View child = this;
4270        ViewParent parent = mParent;
4271        boolean scrolled = false;
4272        while (parent != null) {
4273            scrolled |= parent.requestChildRectangleOnScreen(child,
4274                    rectangle, immediate);
4275
4276            // offset rect so next call has the rectangle in the
4277            // coordinate system of its direct child.
4278            rectangle.offset(child.getLeft(), child.getTop());
4279            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4280
4281            if (!(parent instanceof View)) {
4282                break;
4283            }
4284
4285            child = (View) parent;
4286            parent = child.getParent();
4287        }
4288        return scrolled;
4289    }
4290
4291    /**
4292     * Called when this view wants to give up focus. If focus is cleared
4293     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4294     * <p>
4295     * <strong>Note:</strong> When a View clears focus the framework is trying
4296     * to give focus to the first focusable View from the top. Hence, if this
4297     * View is the first from the top that can take focus, then all callbacks
4298     * related to clearing focus will be invoked after wich the framework will
4299     * give focus to this view.
4300     * </p>
4301     */
4302    public void clearFocus() {
4303        if (DBG) {
4304            System.out.println(this + " clearFocus()");
4305        }
4306
4307        if ((mPrivateFlags & FOCUSED) != 0) {
4308            mPrivateFlags &= ~FOCUSED;
4309
4310            if (mParent != null) {
4311                mParent.clearChildFocus(this);
4312            }
4313
4314            onFocusChanged(false, 0, null);
4315
4316            refreshDrawableState();
4317
4318            ensureInputFocusOnFirstFocusable();
4319
4320            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4321                notifyAccessibilityStateChanged();
4322            }
4323        }
4324    }
4325
4326    void ensureInputFocusOnFirstFocusable() {
4327        View root = getRootView();
4328        if (root != null) {
4329            root.requestFocus();
4330        }
4331    }
4332
4333    /**
4334     * Called internally by the view system when a new view is getting focus.
4335     * This is what clears the old focus.
4336     */
4337    void unFocus() {
4338        if (DBG) {
4339            System.out.println(this + " unFocus()");
4340        }
4341
4342        if ((mPrivateFlags & FOCUSED) != 0) {
4343            mPrivateFlags &= ~FOCUSED;
4344
4345            onFocusChanged(false, 0, null);
4346            refreshDrawableState();
4347
4348            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4349                notifyAccessibilityStateChanged();
4350            }
4351        }
4352    }
4353
4354    /**
4355     * Returns true if this view has focus iteself, or is the ancestor of the
4356     * view that has focus.
4357     *
4358     * @return True if this view has or contains focus, false otherwise.
4359     */
4360    @ViewDebug.ExportedProperty(category = "focus")
4361    public boolean hasFocus() {
4362        return (mPrivateFlags & FOCUSED) != 0;
4363    }
4364
4365    /**
4366     * Returns true if this view is focusable or if it contains a reachable View
4367     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4368     * is a View whose parents do not block descendants focus.
4369     *
4370     * Only {@link #VISIBLE} views are considered focusable.
4371     *
4372     * @return True if the view is focusable or if the view contains a focusable
4373     *         View, false otherwise.
4374     *
4375     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4376     */
4377    public boolean hasFocusable() {
4378        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4379    }
4380
4381    /**
4382     * Called by the view system when the focus state of this view changes.
4383     * When the focus change event is caused by directional navigation, direction
4384     * and previouslyFocusedRect provide insight into where the focus is coming from.
4385     * When overriding, be sure to call up through to the super class so that
4386     * the standard focus handling will occur.
4387     *
4388     * @param gainFocus True if the View has focus; false otherwise.
4389     * @param direction The direction focus has moved when requestFocus()
4390     *                  is called to give this view focus. Values are
4391     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4392     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4393     *                  It may not always apply, in which case use the default.
4394     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4395     *        system, of the previously focused view.  If applicable, this will be
4396     *        passed in as finer grained information about where the focus is coming
4397     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4398     */
4399    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4400        if (gainFocus) {
4401            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4402                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4403            }
4404        }
4405
4406        InputMethodManager imm = InputMethodManager.peekInstance();
4407        if (!gainFocus) {
4408            if (isPressed()) {
4409                setPressed(false);
4410            }
4411            if (imm != null && mAttachInfo != null
4412                    && mAttachInfo.mHasWindowFocus) {
4413                imm.focusOut(this);
4414            }
4415            onFocusLost();
4416        } else if (imm != null && mAttachInfo != null
4417                && mAttachInfo.mHasWindowFocus) {
4418            imm.focusIn(this);
4419        }
4420
4421        invalidate(true);
4422        ListenerInfo li = mListenerInfo;
4423        if (li != null && li.mOnFocusChangeListener != null) {
4424            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4425        }
4426
4427        if (mAttachInfo != null) {
4428            mAttachInfo.mKeyDispatchState.reset(this);
4429        }
4430    }
4431
4432    /**
4433     * Sends an accessibility event of the given type. If accessiiblity is
4434     * not enabled this method has no effect. The default implementation calls
4435     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4436     * to populate information about the event source (this View), then calls
4437     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4438     * populate the text content of the event source including its descendants,
4439     * and last calls
4440     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4441     * on its parent to resuest sending of the event to interested parties.
4442     * <p>
4443     * If an {@link AccessibilityDelegate} has been specified via calling
4444     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4445     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4446     * responsible for handling this call.
4447     * </p>
4448     *
4449     * @param eventType The type of the event to send, as defined by several types from
4450     * {@link android.view.accessibility.AccessibilityEvent}, such as
4451     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4452     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4453     *
4454     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4455     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4456     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4457     * @see AccessibilityDelegate
4458     */
4459    public void sendAccessibilityEvent(int eventType) {
4460        if (mAccessibilityDelegate != null) {
4461            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4462        } else {
4463            sendAccessibilityEventInternal(eventType);
4464        }
4465    }
4466
4467    /**
4468     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4469     * {@link AccessibilityEvent} to make an announcement which is related to some
4470     * sort of a context change for which none of the events representing UI transitions
4471     * is a good fit. For example, announcing a new page in a book. If accessibility
4472     * is not enabled this method does nothing.
4473     *
4474     * @param text The announcement text.
4475     */
4476    public void announceForAccessibility(CharSequence text) {
4477        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4478            AccessibilityEvent event = AccessibilityEvent.obtain(
4479                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4480            event.getText().add(text);
4481            sendAccessibilityEventUnchecked(event);
4482        }
4483    }
4484
4485    /**
4486     * @see #sendAccessibilityEvent(int)
4487     *
4488     * Note: Called from the default {@link AccessibilityDelegate}.
4489     */
4490    void sendAccessibilityEventInternal(int eventType) {
4491        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4492            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4493        }
4494    }
4495
4496    /**
4497     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4498     * takes as an argument an empty {@link AccessibilityEvent} and does not
4499     * perform a check whether accessibility is enabled.
4500     * <p>
4501     * If an {@link AccessibilityDelegate} has been specified via calling
4502     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4503     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4504     * is responsible for handling this call.
4505     * </p>
4506     *
4507     * @param event The event to send.
4508     *
4509     * @see #sendAccessibilityEvent(int)
4510     */
4511    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4512        if (mAccessibilityDelegate != null) {
4513            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4514        } else {
4515            sendAccessibilityEventUncheckedInternal(event);
4516        }
4517    }
4518
4519    /**
4520     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4521     *
4522     * Note: Called from the default {@link AccessibilityDelegate}.
4523     */
4524    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4525        if (!isShown()) {
4526            return;
4527        }
4528        onInitializeAccessibilityEvent(event);
4529        // Only a subset of accessibility events populates text content.
4530        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4531            dispatchPopulateAccessibilityEvent(event);
4532        }
4533        // Intercept accessibility focus events fired by virtual nodes to keep
4534        // track of accessibility focus position in such nodes.
4535        final int eventType = event.getEventType();
4536        switch (eventType) {
4537            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4538                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4539                        event.getSourceNodeId());
4540                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4541                    ViewRootImpl viewRootImpl = getViewRootImpl();
4542                    if (viewRootImpl != null) {
4543                        viewRootImpl.setAccessibilityFocusedHost(this);
4544                    }
4545                }
4546            } break;
4547            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4548                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4549                        event.getSourceNodeId());
4550                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4551                    ViewRootImpl viewRootImpl = getViewRootImpl();
4552                    if (viewRootImpl != null) {
4553                        viewRootImpl.setAccessibilityFocusedHost(null);
4554                    }
4555                }
4556            } break;
4557        }
4558        // In the beginning we called #isShown(), so we know that getParent() is not null.
4559        getParent().requestSendAccessibilityEvent(this, event);
4560    }
4561
4562    /**
4563     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4564     * to its children for adding their text content to the event. Note that the
4565     * event text is populated in a separate dispatch path since we add to the
4566     * event not only the text of the source but also the text of all its descendants.
4567     * A typical implementation will call
4568     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4569     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4570     * on each child. Override this method if custom population of the event text
4571     * content is required.
4572     * <p>
4573     * If an {@link AccessibilityDelegate} has been specified via calling
4574     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4575     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4576     * is responsible for handling this call.
4577     * </p>
4578     * <p>
4579     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4580     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4581     * </p>
4582     *
4583     * @param event The event.
4584     *
4585     * @return True if the event population was completed.
4586     */
4587    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4588        if (mAccessibilityDelegate != null) {
4589            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4590        } else {
4591            return dispatchPopulateAccessibilityEventInternal(event);
4592        }
4593    }
4594
4595    /**
4596     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4597     *
4598     * Note: Called from the default {@link AccessibilityDelegate}.
4599     */
4600    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4601        onPopulateAccessibilityEvent(event);
4602        return false;
4603    }
4604
4605    /**
4606     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4607     * giving a chance to this View to populate the accessibility event with its
4608     * text content. While this method is free to modify event
4609     * attributes other than text content, doing so should normally be performed in
4610     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4611     * <p>
4612     * Example: Adding formatted date string to an accessibility event in addition
4613     *          to the text added by the super implementation:
4614     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4615     *     super.onPopulateAccessibilityEvent(event);
4616     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4617     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4618     *         mCurrentDate.getTimeInMillis(), flags);
4619     *     event.getText().add(selectedDateUtterance);
4620     * }</pre>
4621     * <p>
4622     * If an {@link AccessibilityDelegate} has been specified via calling
4623     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4624     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4625     * is responsible for handling this call.
4626     * </p>
4627     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4628     * information to the event, in case the default implementation has basic information to add.
4629     * </p>
4630     *
4631     * @param event The accessibility event which to populate.
4632     *
4633     * @see #sendAccessibilityEvent(int)
4634     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4635     */
4636    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4637        if (mAccessibilityDelegate != null) {
4638            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4639        } else {
4640            onPopulateAccessibilityEventInternal(event);
4641        }
4642    }
4643
4644    /**
4645     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4646     *
4647     * Note: Called from the default {@link AccessibilityDelegate}.
4648     */
4649    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4650
4651    }
4652
4653    /**
4654     * Initializes an {@link AccessibilityEvent} with information about
4655     * this View which is the event source. In other words, the source of
4656     * an accessibility event is the view whose state change triggered firing
4657     * the event.
4658     * <p>
4659     * Example: Setting the password property of an event in addition
4660     *          to properties set by the super implementation:
4661     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4662     *     super.onInitializeAccessibilityEvent(event);
4663     *     event.setPassword(true);
4664     * }</pre>
4665     * <p>
4666     * If an {@link AccessibilityDelegate} has been specified via calling
4667     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4668     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4669     * is responsible for handling this call.
4670     * </p>
4671     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4672     * information to the event, in case the default implementation has basic information to add.
4673     * </p>
4674     * @param event The event to initialize.
4675     *
4676     * @see #sendAccessibilityEvent(int)
4677     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4678     */
4679    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4680        if (mAccessibilityDelegate != null) {
4681            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4682        } else {
4683            onInitializeAccessibilityEventInternal(event);
4684        }
4685    }
4686
4687    /**
4688     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4689     *
4690     * Note: Called from the default {@link AccessibilityDelegate}.
4691     */
4692    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4693        event.setSource(this);
4694        event.setClassName(View.class.getName());
4695        event.setPackageName(getContext().getPackageName());
4696        event.setEnabled(isEnabled());
4697        event.setContentDescription(mContentDescription);
4698
4699        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4700            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4701            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4702                    FOCUSABLES_ALL);
4703            event.setItemCount(focusablesTempList.size());
4704            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4705            focusablesTempList.clear();
4706        }
4707    }
4708
4709    /**
4710     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4711     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4712     * This method is responsible for obtaining an accessibility node info from a
4713     * pool of reusable instances and calling
4714     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4715     * initialize the former.
4716     * <p>
4717     * Note: The client is responsible for recycling the obtained instance by calling
4718     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4719     * </p>
4720     *
4721     * @return A populated {@link AccessibilityNodeInfo}.
4722     *
4723     * @see AccessibilityNodeInfo
4724     */
4725    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4726        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4727        if (provider != null) {
4728            return provider.createAccessibilityNodeInfo(View.NO_ID);
4729        } else {
4730            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4731            onInitializeAccessibilityNodeInfo(info);
4732            return info;
4733        }
4734    }
4735
4736    /**
4737     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4738     * The base implementation sets:
4739     * <ul>
4740     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4741     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4742     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4743     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4744     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4745     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4746     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4747     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4748     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4749     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4750     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4751     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4752     * </ul>
4753     * <p>
4754     * Subclasses should override this method, call the super implementation,
4755     * and set additional attributes.
4756     * </p>
4757     * <p>
4758     * If an {@link AccessibilityDelegate} has been specified via calling
4759     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4760     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4761     * is responsible for handling this call.
4762     * </p>
4763     *
4764     * @param info The instance to initialize.
4765     */
4766    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4767        if (mAccessibilityDelegate != null) {
4768            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4769        } else {
4770            onInitializeAccessibilityNodeInfoInternal(info);
4771        }
4772    }
4773
4774    /**
4775     * Gets the location of this view in screen coordintates.
4776     *
4777     * @param outRect The output location
4778     */
4779    private void getBoundsOnScreen(Rect outRect) {
4780        if (mAttachInfo == null) {
4781            return;
4782        }
4783
4784        RectF position = mAttachInfo.mTmpTransformRect;
4785        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4786
4787        if (!hasIdentityMatrix()) {
4788            getMatrix().mapRect(position);
4789        }
4790
4791        position.offset(mLeft, mTop);
4792
4793        ViewParent parent = mParent;
4794        while (parent instanceof View) {
4795            View parentView = (View) parent;
4796
4797            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4798
4799            if (!parentView.hasIdentityMatrix()) {
4800                parentView.getMatrix().mapRect(position);
4801            }
4802
4803            position.offset(parentView.mLeft, parentView.mTop);
4804
4805            parent = parentView.mParent;
4806        }
4807
4808        if (parent instanceof ViewRootImpl) {
4809            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4810            position.offset(0, -viewRootImpl.mCurScrollY);
4811        }
4812
4813        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4814
4815        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4816                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4817    }
4818
4819    /**
4820     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4821     *
4822     * Note: Called from the default {@link AccessibilityDelegate}.
4823     */
4824    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4825        Rect bounds = mAttachInfo.mTmpInvalRect;
4826        getDrawingRect(bounds);
4827        info.setBoundsInParent(bounds);
4828
4829        getBoundsOnScreen(bounds);
4830        info.setBoundsInScreen(bounds);
4831
4832        ViewParent parent = getParentForAccessibility();
4833        if (parent instanceof View) {
4834            info.setParent((View) parent);
4835        }
4836
4837        info.setVisibleToUser(isVisibleToUser());
4838
4839        info.setPackageName(mContext.getPackageName());
4840        info.setClassName(View.class.getName());
4841        info.setContentDescription(getContentDescription());
4842
4843        info.setEnabled(isEnabled());
4844        info.setClickable(isClickable());
4845        info.setFocusable(isFocusable());
4846        info.setFocused(isFocused());
4847        info.setAccessibilityFocused(isAccessibilityFocused());
4848        info.setSelected(isSelected());
4849        info.setLongClickable(isLongClickable());
4850
4851        // TODO: These make sense only if we are in an AdapterView but all
4852        // views can be selected. Maybe from accessiiblity perspective
4853        // we should report as selectable view in an AdapterView.
4854        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4855        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4856
4857        if (isFocusable()) {
4858            if (isFocused()) {
4859                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4860            } else {
4861                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4862            }
4863        }
4864
4865        if (!isAccessibilityFocused()) {
4866            final int mode = getAccessibilityFocusable();
4867            if (mode == ACCESSIBILITY_FOCUSABLE_YES || mode == ACCESSIBILITY_FOCUSABLE_AUTO) {
4868                info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4869            }
4870        } else {
4871            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4872        }
4873
4874        if (isClickable() && isEnabled()) {
4875            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4876        }
4877
4878        if (isLongClickable() && isEnabled()) {
4879            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4880        }
4881
4882        if (mContentDescription != null && mContentDescription.length() > 0) {
4883            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4884            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4885            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4886                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4887                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4888        }
4889    }
4890
4891    /**
4892     * Computes whether this view is visible to the user. Such a view is
4893     * attached, visible, all its predecessors are visible, it is not clipped
4894     * entirely by its predecessors, and has an alpha greater than zero.
4895     *
4896     * @return Whether the view is visible on the screen.
4897     *
4898     * @hide
4899     */
4900    protected boolean isVisibleToUser() {
4901        return isVisibleToUser(null);
4902    }
4903
4904    /**
4905     * Computes whether the given portion of this view is visible to the user. Such a view is
4906     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4907     * the specified portion is not clipped entirely by its predecessors.
4908     *
4909     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4910     *                    <code>null</code>, and the entire view will be tested in this case.
4911     *                    When <code>true</code> is returned by the function, the actual visible
4912     *                    region will be stored in this parameter; that is, if boundInView is fully
4913     *                    contained within the view, no modification will be made, otherwise regions
4914     *                    outside of the visible area of the view will be clipped.
4915     *
4916     * @return Whether the specified portion of the view is visible on the screen.
4917     *
4918     * @hide
4919     */
4920    protected boolean isVisibleToUser(Rect boundInView) {
4921        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4922        Point offset = mAttachInfo.mPoint;
4923        // The first two checks are made also made by isShown() which
4924        // however traverses the tree up to the parent to catch that.
4925        // Therefore, we do some fail fast check to minimize the up
4926        // tree traversal.
4927        boolean isVisible = mAttachInfo != null
4928            && mAttachInfo.mWindowVisibility == View.VISIBLE
4929            && getAlpha() > 0
4930            && isShown()
4931            && getGlobalVisibleRect(visibleRect, offset);
4932            if (isVisible && boundInView != null) {
4933                visibleRect.offset(-offset.x, -offset.y);
4934                isVisible &= boundInView.intersect(visibleRect);
4935            }
4936            return isVisible;
4937    }
4938
4939    /**
4940     * Sets a delegate for implementing accessibility support via compositon as
4941     * opposed to inheritance. The delegate's primary use is for implementing
4942     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4943     *
4944     * @param delegate The delegate instance.
4945     *
4946     * @see AccessibilityDelegate
4947     */
4948    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4949        mAccessibilityDelegate = delegate;
4950    }
4951
4952    /**
4953     * Gets the provider for managing a virtual view hierarchy rooted at this View
4954     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4955     * that explore the window content.
4956     * <p>
4957     * If this method returns an instance, this instance is responsible for managing
4958     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4959     * View including the one representing the View itself. Similarly the returned
4960     * instance is responsible for performing accessibility actions on any virtual
4961     * view or the root view itself.
4962     * </p>
4963     * <p>
4964     * If an {@link AccessibilityDelegate} has been specified via calling
4965     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4966     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4967     * is responsible for handling this call.
4968     * </p>
4969     *
4970     * @return The provider.
4971     *
4972     * @see AccessibilityNodeProvider
4973     */
4974    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4975        if (mAccessibilityDelegate != null) {
4976            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4977        } else {
4978            return null;
4979        }
4980    }
4981
4982    /**
4983     * Gets the unique identifier of this view on the screen for accessibility purposes.
4984     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4985     *
4986     * @return The view accessibility id.
4987     *
4988     * @hide
4989     */
4990    public int getAccessibilityViewId() {
4991        if (mAccessibilityViewId == NO_ID) {
4992            mAccessibilityViewId = sNextAccessibilityViewId++;
4993        }
4994        return mAccessibilityViewId;
4995    }
4996
4997    /**
4998     * Gets the unique identifier of the window in which this View reseides.
4999     *
5000     * @return The window accessibility id.
5001     *
5002     * @hide
5003     */
5004    public int getAccessibilityWindowId() {
5005        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5006    }
5007
5008    /**
5009     * Gets the {@link View} description. It briefly describes the view and is
5010     * primarily used for accessibility support. Set this property to enable
5011     * better accessibility support for your application. This is especially
5012     * true for views that do not have textual representation (For example,
5013     * ImageButton).
5014     *
5015     * @return The content description.
5016     *
5017     * @attr ref android.R.styleable#View_contentDescription
5018     */
5019    @ViewDebug.ExportedProperty(category = "accessibility")
5020    public CharSequence getContentDescription() {
5021        return mContentDescription;
5022    }
5023
5024    /**
5025     * Sets the {@link View} description. It briefly describes the view and is
5026     * primarily used for accessibility support. Set this property to enable
5027     * better accessibility support for your application. This is especially
5028     * true for views that do not have textual representation (For example,
5029     * ImageButton).
5030     *
5031     * @param contentDescription The content description.
5032     *
5033     * @attr ref android.R.styleable#View_contentDescription
5034     */
5035    @RemotableViewMethod
5036    public void setContentDescription(CharSequence contentDescription) {
5037        mContentDescription = contentDescription;
5038    }
5039
5040    /**
5041     * Invoked whenever this view loses focus, either by losing window focus or by losing
5042     * focus within its window. This method can be used to clear any state tied to the
5043     * focus. For instance, if a button is held pressed with the trackball and the window
5044     * loses focus, this method can be used to cancel the press.
5045     *
5046     * Subclasses of View overriding this method should always call super.onFocusLost().
5047     *
5048     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5049     * @see #onWindowFocusChanged(boolean)
5050     *
5051     * @hide pending API council approval
5052     */
5053    protected void onFocusLost() {
5054        resetPressedState();
5055    }
5056
5057    private void resetPressedState() {
5058        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5059            return;
5060        }
5061
5062        if (isPressed()) {
5063            setPressed(false);
5064
5065            if (!mHasPerformedLongPress) {
5066                removeLongPressCallback();
5067            }
5068        }
5069    }
5070
5071    /**
5072     * Returns true if this view has focus
5073     *
5074     * @return True if this view has focus, false otherwise.
5075     */
5076    @ViewDebug.ExportedProperty(category = "focus")
5077    public boolean isFocused() {
5078        return (mPrivateFlags & FOCUSED) != 0;
5079    }
5080
5081    /**
5082     * Find the view in the hierarchy rooted at this view that currently has
5083     * focus.
5084     *
5085     * @return The view that currently has focus, or null if no focused view can
5086     *         be found.
5087     */
5088    public View findFocus() {
5089        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
5090    }
5091
5092    /**
5093     * Indicates whether this view is one of the set of scrollable containers in
5094     * its window.
5095     *
5096     * @return whether this view is one of the set of scrollable containers in
5097     * its window
5098     *
5099     * @attr ref android.R.styleable#View_isScrollContainer
5100     */
5101    public boolean isScrollContainer() {
5102        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
5103    }
5104
5105    /**
5106     * Change whether this view is one of the set of scrollable containers in
5107     * its window.  This will be used to determine whether the window can
5108     * resize or must pan when a soft input area is open -- scrollable
5109     * containers allow the window to use resize mode since the container
5110     * will appropriately shrink.
5111     *
5112     * @attr ref android.R.styleable#View_isScrollContainer
5113     */
5114    public void setScrollContainer(boolean isScrollContainer) {
5115        if (isScrollContainer) {
5116            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5117                mAttachInfo.mScrollContainers.add(this);
5118                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5119            }
5120            mPrivateFlags |= SCROLL_CONTAINER;
5121        } else {
5122            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5123                mAttachInfo.mScrollContainers.remove(this);
5124            }
5125            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5126        }
5127    }
5128
5129    /**
5130     * Returns the quality of the drawing cache.
5131     *
5132     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5133     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5134     *
5135     * @see #setDrawingCacheQuality(int)
5136     * @see #setDrawingCacheEnabled(boolean)
5137     * @see #isDrawingCacheEnabled()
5138     *
5139     * @attr ref android.R.styleable#View_drawingCacheQuality
5140     */
5141    public int getDrawingCacheQuality() {
5142        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5143    }
5144
5145    /**
5146     * Set the drawing cache quality of this view. This value is used only when the
5147     * drawing cache is enabled
5148     *
5149     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5150     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5151     *
5152     * @see #getDrawingCacheQuality()
5153     * @see #setDrawingCacheEnabled(boolean)
5154     * @see #isDrawingCacheEnabled()
5155     *
5156     * @attr ref android.R.styleable#View_drawingCacheQuality
5157     */
5158    public void setDrawingCacheQuality(int quality) {
5159        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5160    }
5161
5162    /**
5163     * Returns whether the screen should remain on, corresponding to the current
5164     * value of {@link #KEEP_SCREEN_ON}.
5165     *
5166     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5167     *
5168     * @see #setKeepScreenOn(boolean)
5169     *
5170     * @attr ref android.R.styleable#View_keepScreenOn
5171     */
5172    public boolean getKeepScreenOn() {
5173        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5174    }
5175
5176    /**
5177     * Controls whether the screen should remain on, modifying the
5178     * value of {@link #KEEP_SCREEN_ON}.
5179     *
5180     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5181     *
5182     * @see #getKeepScreenOn()
5183     *
5184     * @attr ref android.R.styleable#View_keepScreenOn
5185     */
5186    public void setKeepScreenOn(boolean keepScreenOn) {
5187        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5188    }
5189
5190    /**
5191     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5192     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5193     *
5194     * @attr ref android.R.styleable#View_nextFocusLeft
5195     */
5196    public int getNextFocusLeftId() {
5197        return mNextFocusLeftId;
5198    }
5199
5200    /**
5201     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5202     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5203     * decide automatically.
5204     *
5205     * @attr ref android.R.styleable#View_nextFocusLeft
5206     */
5207    public void setNextFocusLeftId(int nextFocusLeftId) {
5208        mNextFocusLeftId = nextFocusLeftId;
5209    }
5210
5211    /**
5212     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5213     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5214     *
5215     * @attr ref android.R.styleable#View_nextFocusRight
5216     */
5217    public int getNextFocusRightId() {
5218        return mNextFocusRightId;
5219    }
5220
5221    /**
5222     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5223     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5224     * decide automatically.
5225     *
5226     * @attr ref android.R.styleable#View_nextFocusRight
5227     */
5228    public void setNextFocusRightId(int nextFocusRightId) {
5229        mNextFocusRightId = nextFocusRightId;
5230    }
5231
5232    /**
5233     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5234     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5235     *
5236     * @attr ref android.R.styleable#View_nextFocusUp
5237     */
5238    public int getNextFocusUpId() {
5239        return mNextFocusUpId;
5240    }
5241
5242    /**
5243     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5244     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5245     * decide automatically.
5246     *
5247     * @attr ref android.R.styleable#View_nextFocusUp
5248     */
5249    public void setNextFocusUpId(int nextFocusUpId) {
5250        mNextFocusUpId = nextFocusUpId;
5251    }
5252
5253    /**
5254     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5255     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5256     *
5257     * @attr ref android.R.styleable#View_nextFocusDown
5258     */
5259    public int getNextFocusDownId() {
5260        return mNextFocusDownId;
5261    }
5262
5263    /**
5264     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5265     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5266     * decide automatically.
5267     *
5268     * @attr ref android.R.styleable#View_nextFocusDown
5269     */
5270    public void setNextFocusDownId(int nextFocusDownId) {
5271        mNextFocusDownId = nextFocusDownId;
5272    }
5273
5274    /**
5275     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5276     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5277     *
5278     * @attr ref android.R.styleable#View_nextFocusForward
5279     */
5280    public int getNextFocusForwardId() {
5281        return mNextFocusForwardId;
5282    }
5283
5284    /**
5285     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5286     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5287     * decide automatically.
5288     *
5289     * @attr ref android.R.styleable#View_nextFocusForward
5290     */
5291    public void setNextFocusForwardId(int nextFocusForwardId) {
5292        mNextFocusForwardId = nextFocusForwardId;
5293    }
5294
5295    /**
5296     * Returns the visibility of this view and all of its ancestors
5297     *
5298     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5299     */
5300    public boolean isShown() {
5301        View current = this;
5302        //noinspection ConstantConditions
5303        do {
5304            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5305                return false;
5306            }
5307            ViewParent parent = current.mParent;
5308            if (parent == null) {
5309                return false; // We are not attached to the view root
5310            }
5311            if (!(parent instanceof View)) {
5312                return true;
5313            }
5314            current = (View) parent;
5315        } while (current != null);
5316
5317        return false;
5318    }
5319
5320    /**
5321     * Called by the view hierarchy when the content insets for a window have
5322     * changed, to allow it to adjust its content to fit within those windows.
5323     * The content insets tell you the space that the status bar, input method,
5324     * and other system windows infringe on the application's window.
5325     *
5326     * <p>You do not normally need to deal with this function, since the default
5327     * window decoration given to applications takes care of applying it to the
5328     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5329     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5330     * and your content can be placed under those system elements.  You can then
5331     * use this method within your view hierarchy if you have parts of your UI
5332     * which you would like to ensure are not being covered.
5333     *
5334     * <p>The default implementation of this method simply applies the content
5335     * inset's to the view's padding, consuming that content (modifying the
5336     * insets to be 0), and returning true.  This behavior is off by default, but can
5337     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5338     *
5339     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5340     * insets object is propagated down the hierarchy, so any changes made to it will
5341     * be seen by all following views (including potentially ones above in
5342     * the hierarchy since this is a depth-first traversal).  The first view
5343     * that returns true will abort the entire traversal.
5344     *
5345     * <p>The default implementation works well for a situation where it is
5346     * used with a container that covers the entire window, allowing it to
5347     * apply the appropriate insets to its content on all edges.  If you need
5348     * a more complicated layout (such as two different views fitting system
5349     * windows, one on the top of the window, and one on the bottom),
5350     * you can override the method and handle the insets however you would like.
5351     * Note that the insets provided by the framework are always relative to the
5352     * far edges of the window, not accounting for the location of the called view
5353     * within that window.  (In fact when this method is called you do not yet know
5354     * where the layout will place the view, as it is done before layout happens.)
5355     *
5356     * <p>Note: unlike many View methods, there is no dispatch phase to this
5357     * call.  If you are overriding it in a ViewGroup and want to allow the
5358     * call to continue to your children, you must be sure to call the super
5359     * implementation.
5360     *
5361     * <p>Here is a sample layout that makes use of fitting system windows
5362     * to have controls for a video view placed inside of the window decorations
5363     * that it hides and shows.  This can be used with code like the second
5364     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5365     *
5366     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5367     *
5368     * @param insets Current content insets of the window.  Prior to
5369     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5370     * the insets or else you and Android will be unhappy.
5371     *
5372     * @return Return true if this view applied the insets and it should not
5373     * continue propagating further down the hierarchy, false otherwise.
5374     * @see #getFitsSystemWindows()
5375     * @see #setFitsSystemWindows()
5376     * @see #setSystemUiVisibility(int)
5377     */
5378    protected boolean fitSystemWindows(Rect insets) {
5379        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5380            mUserPaddingStart = -1;
5381            mUserPaddingEnd = -1;
5382            mUserPaddingRelative = false;
5383            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5384                    || mAttachInfo == null
5385                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5386                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5387                return true;
5388            } else {
5389                internalSetPadding(0, 0, 0, 0);
5390                return false;
5391            }
5392        }
5393        return false;
5394    }
5395
5396    /**
5397     * Sets whether or not this view should account for system screen decorations
5398     * such as the status bar and inset its content; that is, controlling whether
5399     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5400     * executed.  See that method for more details.
5401     *
5402     * <p>Note that if you are providing your own implementation of
5403     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5404     * flag to true -- your implementation will be overriding the default
5405     * implementation that checks this flag.
5406     *
5407     * @param fitSystemWindows If true, then the default implementation of
5408     * {@link #fitSystemWindows(Rect)} will be executed.
5409     *
5410     * @attr ref android.R.styleable#View_fitsSystemWindows
5411     * @see #getFitsSystemWindows()
5412     * @see #fitSystemWindows(Rect)
5413     * @see #setSystemUiVisibility(int)
5414     */
5415    public void setFitsSystemWindows(boolean fitSystemWindows) {
5416        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5417    }
5418
5419    /**
5420     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5421     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5422     * will be executed.
5423     *
5424     * @return Returns true if the default implementation of
5425     * {@link #fitSystemWindows(Rect)} will be executed.
5426     *
5427     * @attr ref android.R.styleable#View_fitsSystemWindows
5428     * @see #setFitsSystemWindows()
5429     * @see #fitSystemWindows(Rect)
5430     * @see #setSystemUiVisibility(int)
5431     */
5432    public boolean getFitsSystemWindows() {
5433        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5434    }
5435
5436    /** @hide */
5437    public boolean fitsSystemWindows() {
5438        return getFitsSystemWindows();
5439    }
5440
5441    /**
5442     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5443     */
5444    public void requestFitSystemWindows() {
5445        if (mParent != null) {
5446            mParent.requestFitSystemWindows();
5447        }
5448    }
5449
5450    /**
5451     * For use by PhoneWindow to make its own system window fitting optional.
5452     * @hide
5453     */
5454    public void makeOptionalFitsSystemWindows() {
5455        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5456    }
5457
5458    /**
5459     * Returns the visibility status for this view.
5460     *
5461     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5462     * @attr ref android.R.styleable#View_visibility
5463     */
5464    @ViewDebug.ExportedProperty(mapping = {
5465        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5466        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5467        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5468    })
5469    public int getVisibility() {
5470        return mViewFlags & VISIBILITY_MASK;
5471    }
5472
5473    /**
5474     * Set the enabled state of this view.
5475     *
5476     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5477     * @attr ref android.R.styleable#View_visibility
5478     */
5479    @RemotableViewMethod
5480    public void setVisibility(int visibility) {
5481        setFlags(visibility, VISIBILITY_MASK);
5482        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5483    }
5484
5485    /**
5486     * Returns the enabled status for this view. The interpretation of the
5487     * enabled state varies by subclass.
5488     *
5489     * @return True if this view is enabled, false otherwise.
5490     */
5491    @ViewDebug.ExportedProperty
5492    public boolean isEnabled() {
5493        return (mViewFlags & ENABLED_MASK) == ENABLED;
5494    }
5495
5496    /**
5497     * Set the enabled state of this view. The interpretation of the enabled
5498     * state varies by subclass.
5499     *
5500     * @param enabled True if this view is enabled, false otherwise.
5501     */
5502    @RemotableViewMethod
5503    public void setEnabled(boolean enabled) {
5504        if (enabled == isEnabled()) return;
5505
5506        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5507
5508        /*
5509         * The View most likely has to change its appearance, so refresh
5510         * the drawable state.
5511         */
5512        refreshDrawableState();
5513
5514        // Invalidate too, since the default behavior for views is to be
5515        // be drawn at 50% alpha rather than to change the drawable.
5516        invalidate(true);
5517    }
5518
5519    /**
5520     * Set whether this view can receive the focus.
5521     *
5522     * Setting this to false will also ensure that this view is not focusable
5523     * in touch mode.
5524     *
5525     * @param focusable If true, this view can receive the focus.
5526     *
5527     * @see #setFocusableInTouchMode(boolean)
5528     * @attr ref android.R.styleable#View_focusable
5529     */
5530    public void setFocusable(boolean focusable) {
5531        if (!focusable) {
5532            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5533        }
5534        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5535    }
5536
5537    /**
5538     * Set whether this view can receive focus while in touch mode.
5539     *
5540     * Setting this to true will also ensure that this view is focusable.
5541     *
5542     * @param focusableInTouchMode If true, this view can receive the focus while
5543     *   in touch mode.
5544     *
5545     * @see #setFocusable(boolean)
5546     * @attr ref android.R.styleable#View_focusableInTouchMode
5547     */
5548    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5549        // Focusable in touch mode should always be set before the focusable flag
5550        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5551        // which, in touch mode, will not successfully request focus on this view
5552        // because the focusable in touch mode flag is not set
5553        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5554        if (focusableInTouchMode) {
5555            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5556        }
5557    }
5558
5559    /**
5560     * Set whether this view should have sound effects enabled for events such as
5561     * clicking and touching.
5562     *
5563     * <p>You may wish to disable sound effects for a view if you already play sounds,
5564     * for instance, a dial key that plays dtmf tones.
5565     *
5566     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5567     * @see #isSoundEffectsEnabled()
5568     * @see #playSoundEffect(int)
5569     * @attr ref android.R.styleable#View_soundEffectsEnabled
5570     */
5571    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5572        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5573    }
5574
5575    /**
5576     * @return whether this view should have sound effects enabled for events such as
5577     *     clicking and touching.
5578     *
5579     * @see #setSoundEffectsEnabled(boolean)
5580     * @see #playSoundEffect(int)
5581     * @attr ref android.R.styleable#View_soundEffectsEnabled
5582     */
5583    @ViewDebug.ExportedProperty
5584    public boolean isSoundEffectsEnabled() {
5585        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5586    }
5587
5588    /**
5589     * Set whether this view should have haptic feedback for events such as
5590     * long presses.
5591     *
5592     * <p>You may wish to disable haptic feedback if your view already controls
5593     * its own haptic feedback.
5594     *
5595     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5596     * @see #isHapticFeedbackEnabled()
5597     * @see #performHapticFeedback(int)
5598     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5599     */
5600    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5601        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5602    }
5603
5604    /**
5605     * @return whether this view should have haptic feedback enabled for events
5606     * long presses.
5607     *
5608     * @see #setHapticFeedbackEnabled(boolean)
5609     * @see #performHapticFeedback(int)
5610     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5611     */
5612    @ViewDebug.ExportedProperty
5613    public boolean isHapticFeedbackEnabled() {
5614        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5615    }
5616
5617    /**
5618     * Returns the layout direction for this view.
5619     *
5620     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5621     *   {@link #LAYOUT_DIRECTION_RTL},
5622     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5623     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5624     *
5625     * @attr ref android.R.styleable#View_layoutDirection
5626     * @hide
5627     */
5628    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5629        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5630        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5631        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5632        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5633    })
5634    public int getLayoutDirection() {
5635        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5636    }
5637
5638    /**
5639     * Set the layout direction for this view. This will propagate a reset of layout direction
5640     * resolution to the view's children and resolve layout direction for this view.
5641     *
5642     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5643     *   {@link #LAYOUT_DIRECTION_RTL},
5644     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5645     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5646     *
5647     * @attr ref android.R.styleable#View_layoutDirection
5648     * @hide
5649     */
5650    @RemotableViewMethod
5651    public void setLayoutDirection(int layoutDirection) {
5652        if (getLayoutDirection() != layoutDirection) {
5653            // Reset the current layout direction and the resolved one
5654            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5655            resetResolvedLayoutDirection();
5656            // Set the new layout direction (filtered) and ask for a layout pass
5657            mPrivateFlags2 |=
5658                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5659            requestLayout();
5660        }
5661    }
5662
5663    /**
5664     * Returns the resolved layout direction for this view.
5665     *
5666     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5667     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5668     * @hide
5669     */
5670    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5671        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5672        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5673    })
5674    public int getResolvedLayoutDirection() {
5675        // The layout diretion will be resolved only if needed
5676        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5677            resolveLayoutDirection();
5678        }
5679        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5680                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5681    }
5682
5683    /**
5684     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5685     * layout attribute and/or the inherited value from the parent
5686     *
5687     * @return true if the layout is right-to-left.
5688     * @hide
5689     */
5690    @ViewDebug.ExportedProperty(category = "layout")
5691    public boolean isLayoutRtl() {
5692        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5693    }
5694
5695    /**
5696     * Indicates whether the view is currently tracking transient state that the
5697     * app should not need to concern itself with saving and restoring, but that
5698     * the framework should take special note to preserve when possible.
5699     *
5700     * <p>A view with transient state cannot be trivially rebound from an external
5701     * data source, such as an adapter binding item views in a list. This may be
5702     * because the view is performing an animation, tracking user selection
5703     * of content, or similar.</p>
5704     *
5705     * @return true if the view has transient state
5706     */
5707    @ViewDebug.ExportedProperty(category = "layout")
5708    public boolean hasTransientState() {
5709        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5710    }
5711
5712    /**
5713     * Set whether this view is currently tracking transient state that the
5714     * framework should attempt to preserve when possible. This flag is reference counted,
5715     * so every call to setHasTransientState(true) should be paired with a later call
5716     * to setHasTransientState(false).
5717     *
5718     * <p>A view with transient state cannot be trivially rebound from an external
5719     * data source, such as an adapter binding item views in a list. This may be
5720     * because the view is performing an animation, tracking user selection
5721     * of content, or similar.</p>
5722     *
5723     * @param hasTransientState true if this view has transient state
5724     */
5725    public void setHasTransientState(boolean hasTransientState) {
5726        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5727                mTransientStateCount - 1;
5728        if (mTransientStateCount < 0) {
5729            mTransientStateCount = 0;
5730            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5731                    "unmatched pair of setHasTransientState calls");
5732        }
5733        if ((hasTransientState && mTransientStateCount == 1) ||
5734                (!hasTransientState && mTransientStateCount == 0)) {
5735            // update flag if we've just incremented up from 0 or decremented down to 0
5736            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5737                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5738            if (mParent != null) {
5739                try {
5740                    mParent.childHasTransientStateChanged(this, hasTransientState);
5741                } catch (AbstractMethodError e) {
5742                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5743                            " does not fully implement ViewParent", e);
5744                }
5745            }
5746        }
5747    }
5748
5749    /**
5750     * If this view doesn't do any drawing on its own, set this flag to
5751     * allow further optimizations. By default, this flag is not set on
5752     * View, but could be set on some View subclasses such as ViewGroup.
5753     *
5754     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5755     * you should clear this flag.
5756     *
5757     * @param willNotDraw whether or not this View draw on its own
5758     */
5759    public void setWillNotDraw(boolean willNotDraw) {
5760        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5761    }
5762
5763    /**
5764     * Returns whether or not this View draws on its own.
5765     *
5766     * @return true if this view has nothing to draw, false otherwise
5767     */
5768    @ViewDebug.ExportedProperty(category = "drawing")
5769    public boolean willNotDraw() {
5770        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5771    }
5772
5773    /**
5774     * When a View's drawing cache is enabled, drawing is redirected to an
5775     * offscreen bitmap. Some views, like an ImageView, must be able to
5776     * bypass this mechanism if they already draw a single bitmap, to avoid
5777     * unnecessary usage of the memory.
5778     *
5779     * @param willNotCacheDrawing true if this view does not cache its
5780     *        drawing, false otherwise
5781     */
5782    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5783        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5784    }
5785
5786    /**
5787     * Returns whether or not this View can cache its drawing or not.
5788     *
5789     * @return true if this view does not cache its drawing, false otherwise
5790     */
5791    @ViewDebug.ExportedProperty(category = "drawing")
5792    public boolean willNotCacheDrawing() {
5793        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5794    }
5795
5796    /**
5797     * Indicates whether this view reacts to click events or not.
5798     *
5799     * @return true if the view is clickable, false otherwise
5800     *
5801     * @see #setClickable(boolean)
5802     * @attr ref android.R.styleable#View_clickable
5803     */
5804    @ViewDebug.ExportedProperty
5805    public boolean isClickable() {
5806        return (mViewFlags & CLICKABLE) == CLICKABLE;
5807    }
5808
5809    /**
5810     * Enables or disables click events for this view. When a view
5811     * is clickable it will change its state to "pressed" on every click.
5812     * Subclasses should set the view clickable to visually react to
5813     * user's clicks.
5814     *
5815     * @param clickable true to make the view clickable, false otherwise
5816     *
5817     * @see #isClickable()
5818     * @attr ref android.R.styleable#View_clickable
5819     */
5820    public void setClickable(boolean clickable) {
5821        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5822    }
5823
5824    /**
5825     * Indicates whether this view reacts to long click events or not.
5826     *
5827     * @return true if the view is long clickable, false otherwise
5828     *
5829     * @see #setLongClickable(boolean)
5830     * @attr ref android.R.styleable#View_longClickable
5831     */
5832    public boolean isLongClickable() {
5833        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5834    }
5835
5836    /**
5837     * Enables or disables long click events for this view. When a view is long
5838     * clickable it reacts to the user holding down the button for a longer
5839     * duration than a tap. This event can either launch the listener or a
5840     * context menu.
5841     *
5842     * @param longClickable true to make the view long clickable, false otherwise
5843     * @see #isLongClickable()
5844     * @attr ref android.R.styleable#View_longClickable
5845     */
5846    public void setLongClickable(boolean longClickable) {
5847        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5848    }
5849
5850    /**
5851     * Sets the pressed state for this view.
5852     *
5853     * @see #isClickable()
5854     * @see #setClickable(boolean)
5855     *
5856     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5857     *        the View's internal state from a previously set "pressed" state.
5858     */
5859    public void setPressed(boolean pressed) {
5860        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5861
5862        if (pressed) {
5863            mPrivateFlags |= PRESSED;
5864        } else {
5865            mPrivateFlags &= ~PRESSED;
5866        }
5867
5868        if (needsRefresh) {
5869            refreshDrawableState();
5870        }
5871        dispatchSetPressed(pressed);
5872    }
5873
5874    /**
5875     * Dispatch setPressed to all of this View's children.
5876     *
5877     * @see #setPressed(boolean)
5878     *
5879     * @param pressed The new pressed state
5880     */
5881    protected void dispatchSetPressed(boolean pressed) {
5882    }
5883
5884    /**
5885     * Indicates whether the view is currently in pressed state. Unless
5886     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5887     * the pressed state.
5888     *
5889     * @see #setPressed(boolean)
5890     * @see #isClickable()
5891     * @see #setClickable(boolean)
5892     *
5893     * @return true if the view is currently pressed, false otherwise
5894     */
5895    public boolean isPressed() {
5896        return (mPrivateFlags & PRESSED) == PRESSED;
5897    }
5898
5899    /**
5900     * Indicates whether this view will save its state (that is,
5901     * whether its {@link #onSaveInstanceState} method will be called).
5902     *
5903     * @return Returns true if the view state saving is enabled, else false.
5904     *
5905     * @see #setSaveEnabled(boolean)
5906     * @attr ref android.R.styleable#View_saveEnabled
5907     */
5908    public boolean isSaveEnabled() {
5909        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5910    }
5911
5912    /**
5913     * Controls whether the saving of this view's state is
5914     * enabled (that is, whether its {@link #onSaveInstanceState} method
5915     * will be called).  Note that even if freezing is enabled, the
5916     * view still must have an id assigned to it (via {@link #setId(int)})
5917     * for its state to be saved.  This flag can only disable the
5918     * saving of this view; any child views may still have their state saved.
5919     *
5920     * @param enabled Set to false to <em>disable</em> state saving, or true
5921     * (the default) to allow it.
5922     *
5923     * @see #isSaveEnabled()
5924     * @see #setId(int)
5925     * @see #onSaveInstanceState()
5926     * @attr ref android.R.styleable#View_saveEnabled
5927     */
5928    public void setSaveEnabled(boolean enabled) {
5929        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5930    }
5931
5932    /**
5933     * Gets whether the framework should discard touches when the view's
5934     * window is obscured by another visible window.
5935     * Refer to the {@link View} security documentation for more details.
5936     *
5937     * @return True if touch filtering is enabled.
5938     *
5939     * @see #setFilterTouchesWhenObscured(boolean)
5940     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5941     */
5942    @ViewDebug.ExportedProperty
5943    public boolean getFilterTouchesWhenObscured() {
5944        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5945    }
5946
5947    /**
5948     * Sets whether the framework should discard touches when the view's
5949     * window is obscured by another visible window.
5950     * Refer to the {@link View} security documentation for more details.
5951     *
5952     * @param enabled True if touch filtering should be enabled.
5953     *
5954     * @see #getFilterTouchesWhenObscured
5955     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5956     */
5957    public void setFilterTouchesWhenObscured(boolean enabled) {
5958        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5959                FILTER_TOUCHES_WHEN_OBSCURED);
5960    }
5961
5962    /**
5963     * Indicates whether the entire hierarchy under this view will save its
5964     * state when a state saving traversal occurs from its parent.  The default
5965     * is true; if false, these views will not be saved unless
5966     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5967     *
5968     * @return Returns true if the view state saving from parent is enabled, else false.
5969     *
5970     * @see #setSaveFromParentEnabled(boolean)
5971     */
5972    public boolean isSaveFromParentEnabled() {
5973        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5974    }
5975
5976    /**
5977     * Controls whether the entire hierarchy under this view will save its
5978     * state when a state saving traversal occurs from its parent.  The default
5979     * is true; if false, these views will not be saved unless
5980     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5981     *
5982     * @param enabled Set to false to <em>disable</em> state saving, or true
5983     * (the default) to allow it.
5984     *
5985     * @see #isSaveFromParentEnabled()
5986     * @see #setId(int)
5987     * @see #onSaveInstanceState()
5988     */
5989    public void setSaveFromParentEnabled(boolean enabled) {
5990        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5991    }
5992
5993
5994    /**
5995     * Returns whether this View is able to take focus.
5996     *
5997     * @return True if this view can take focus, or false otherwise.
5998     * @attr ref android.R.styleable#View_focusable
5999     */
6000    @ViewDebug.ExportedProperty(category = "focus")
6001    public final boolean isFocusable() {
6002        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6003    }
6004
6005    /**
6006     * When a view is focusable, it may not want to take focus when in touch mode.
6007     * For example, a button would like focus when the user is navigating via a D-pad
6008     * so that the user can click on it, but once the user starts touching the screen,
6009     * the button shouldn't take focus
6010     * @return Whether the view is focusable in touch mode.
6011     * @attr ref android.R.styleable#View_focusableInTouchMode
6012     */
6013    @ViewDebug.ExportedProperty
6014    public final boolean isFocusableInTouchMode() {
6015        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6016    }
6017
6018    /**
6019     * Find the nearest view in the specified direction that can take focus.
6020     * This does not actually give focus to that view.
6021     *
6022     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6023     *
6024     * @return The nearest focusable in the specified direction, or null if none
6025     *         can be found.
6026     */
6027    public View focusSearch(int direction) {
6028        if (mParent != null) {
6029            return mParent.focusSearch(this, direction);
6030        } else {
6031            return null;
6032        }
6033    }
6034
6035    /**
6036     * This method is the last chance for the focused view and its ancestors to
6037     * respond to an arrow key. This is called when the focused view did not
6038     * consume the key internally, nor could the view system find a new view in
6039     * the requested direction to give focus to.
6040     *
6041     * @param focused The currently focused view.
6042     * @param direction The direction focus wants to move. One of FOCUS_UP,
6043     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6044     * @return True if the this view consumed this unhandled move.
6045     */
6046    public boolean dispatchUnhandledMove(View focused, int direction) {
6047        return false;
6048    }
6049
6050    /**
6051     * If a user manually specified the next view id for a particular direction,
6052     * use the root to look up the view.
6053     * @param root The root view of the hierarchy containing this view.
6054     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6055     * or FOCUS_BACKWARD.
6056     * @return The user specified next view, or null if there is none.
6057     */
6058    View findUserSetNextFocus(View root, int direction) {
6059        switch (direction) {
6060            case FOCUS_LEFT:
6061                if (mNextFocusLeftId == View.NO_ID) return null;
6062                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6063            case FOCUS_RIGHT:
6064                if (mNextFocusRightId == View.NO_ID) return null;
6065                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6066            case FOCUS_UP:
6067                if (mNextFocusUpId == View.NO_ID) return null;
6068                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6069            case FOCUS_DOWN:
6070                if (mNextFocusDownId == View.NO_ID) return null;
6071                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6072            case FOCUS_FORWARD:
6073                if (mNextFocusForwardId == View.NO_ID) return null;
6074                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6075            case FOCUS_BACKWARD: {
6076                if (mID == View.NO_ID) return null;
6077                final int id = mID;
6078                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6079                    @Override
6080                    public boolean apply(View t) {
6081                        return t.mNextFocusForwardId == id;
6082                    }
6083                });
6084            }
6085        }
6086        return null;
6087    }
6088
6089    private View findViewInsideOutShouldExist(View root, final int childViewId) {
6090        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6091            @Override
6092            public boolean apply(View t) {
6093                return t.mID == childViewId;
6094            }
6095        });
6096
6097        if (result == null) {
6098            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
6099                    + "by user for id " + childViewId);
6100        }
6101        return result;
6102    }
6103
6104    /**
6105     * Find and return all focusable views that are descendants of this view,
6106     * possibly including this view if it is focusable itself.
6107     *
6108     * @param direction The direction of the focus
6109     * @return A list of focusable views
6110     */
6111    public ArrayList<View> getFocusables(int direction) {
6112        ArrayList<View> result = new ArrayList<View>(24);
6113        addFocusables(result, direction);
6114        return result;
6115    }
6116
6117    /**
6118     * Add any focusable views that are descendants of this view (possibly
6119     * including this view if it is focusable itself) to views.  If we are in touch mode,
6120     * only add views that are also focusable in touch mode.
6121     *
6122     * @param views Focusable views found so far
6123     * @param direction The direction of the focus
6124     */
6125    public void addFocusables(ArrayList<View> views, int direction) {
6126        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6127    }
6128
6129    /**
6130     * Adds any focusable views that are descendants of this view (possibly
6131     * including this view if it is focusable itself) to views. This method
6132     * adds all focusable views regardless if we are in touch mode or
6133     * only views focusable in touch mode if we are in touch mode or
6134     * only views that can take accessibility focus if accessibility is enabeld
6135     * depending on the focusable mode paramater.
6136     *
6137     * @param views Focusable views found so far or null if all we are interested is
6138     *        the number of focusables.
6139     * @param direction The direction of the focus.
6140     * @param focusableMode The type of focusables to be added.
6141     *
6142     * @see #FOCUSABLES_ALL
6143     * @see #FOCUSABLES_TOUCH_MODE
6144     */
6145    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6146        if (views == null) {
6147            return;
6148        }
6149        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
6150            if (isAccessibilityFocusable()) {
6151                views.add(this);
6152                return;
6153            }
6154        }
6155        if (!isFocusable()) {
6156            return;
6157        }
6158        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6159                && isInTouchMode() && !isFocusableInTouchMode()) {
6160            return;
6161        }
6162        views.add(this);
6163    }
6164
6165    /**
6166     * Finds the Views that contain given text. The containment is case insensitive.
6167     * The search is performed by either the text that the View renders or the content
6168     * description that describes the view for accessibility purposes and the view does
6169     * not render or both. Clients can specify how the search is to be performed via
6170     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6171     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6172     *
6173     * @param outViews The output list of matching Views.
6174     * @param searched The text to match against.
6175     *
6176     * @see #FIND_VIEWS_WITH_TEXT
6177     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6178     * @see #setContentDescription(CharSequence)
6179     */
6180    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6181        if (getAccessibilityNodeProvider() != null) {
6182            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6183                outViews.add(this);
6184            }
6185        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6186                && (searched != null && searched.length() > 0)
6187                && (mContentDescription != null && mContentDescription.length() > 0)) {
6188            String searchedLowerCase = searched.toString().toLowerCase();
6189            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6190            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6191                outViews.add(this);
6192            }
6193        }
6194    }
6195
6196    /**
6197     * Find and return all touchable views that are descendants of this view,
6198     * possibly including this view if it is touchable itself.
6199     *
6200     * @return A list of touchable views
6201     */
6202    public ArrayList<View> getTouchables() {
6203        ArrayList<View> result = new ArrayList<View>();
6204        addTouchables(result);
6205        return result;
6206    }
6207
6208    /**
6209     * Add any touchable views that are descendants of this view (possibly
6210     * including this view if it is touchable itself) to views.
6211     *
6212     * @param views Touchable views found so far
6213     */
6214    public void addTouchables(ArrayList<View> views) {
6215        final int viewFlags = mViewFlags;
6216
6217        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6218                && (viewFlags & ENABLED_MASK) == ENABLED) {
6219            views.add(this);
6220        }
6221    }
6222
6223    /**
6224     * Returns whether this View is accessibility focused.
6225     *
6226     * @return True if this View is accessibility focused.
6227     */
6228    boolean isAccessibilityFocused() {
6229        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6230    }
6231
6232    /**
6233     * Call this to try to give accessibility focus to this view.
6234     *
6235     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6236     * returns false or the view is no visible or the view already has accessibility
6237     * focus.
6238     *
6239     * See also {@link #focusSearch(int)}, which is what you call to say that you
6240     * have focus, and you want your parent to look for the next one.
6241     *
6242     * @return Whether this view actually took accessibility focus.
6243     *
6244     * @hide
6245     */
6246    public boolean requestAccessibilityFocus() {
6247        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6248        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6249            return false;
6250        }
6251        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6252            return false;
6253        }
6254        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6255            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6256            ViewRootImpl viewRootImpl = getViewRootImpl();
6257            if (viewRootImpl != null) {
6258                viewRootImpl.setAccessibilityFocusedHost(this);
6259            }
6260            invalidate();
6261            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6262            notifyAccessibilityStateChanged();
6263            return true;
6264        }
6265        return false;
6266    }
6267
6268    /**
6269     * Call this to try to clear accessibility focus of this view.
6270     *
6271     * See also {@link #focusSearch(int)}, which is what you call to say that you
6272     * have focus, and you want your parent to look for the next one.
6273     *
6274     * @hide
6275     */
6276    public void clearAccessibilityFocus() {
6277        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6278            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6279            invalidate();
6280            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6281            notifyAccessibilityStateChanged();
6282            // Clear the text navigation state.
6283            setAccessibilityCursorPosition(ACCESSIBILITY_CURSOR_POSITION_UNDEFINED);
6284        }
6285        // Clear the global reference of accessibility focus if this
6286        // view or any of its descendants had accessibility focus.
6287        ViewRootImpl viewRootImpl = getViewRootImpl();
6288        if (viewRootImpl != null) {
6289            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6290            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6291                viewRootImpl.setAccessibilityFocusedHost(null);
6292            }
6293        }
6294    }
6295
6296    private void requestAccessibilityFocusFromHover() {
6297        if (includeForAccessibility() && isActionableForAccessibility()) {
6298            requestAccessibilityFocus();
6299            requestFocusNoSearch(View.FOCUS_DOWN, null);
6300        } else {
6301            if (mParent != null) {
6302                View nextFocus = mParent.findViewToTakeAccessibilityFocusFromHover(this, this);
6303                if (nextFocus != null) {
6304                    nextFocus.requestAccessibilityFocus();
6305                    nextFocus.requestFocusNoSearch(View.FOCUS_DOWN, null);
6306                }
6307            }
6308        }
6309    }
6310
6311    private boolean canTakeAccessibilityFocusFromHover() {
6312        if (includeForAccessibility() && isActionableForAccessibility()) {
6313            return true;
6314        }
6315        if (mParent != null) {
6316            return (mParent.findViewToTakeAccessibilityFocusFromHover(this, this) == this);
6317        }
6318        return false;
6319    }
6320
6321    /**
6322     * Clears accessibility focus without calling any callback methods
6323     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6324     * is used for clearing accessibility focus when giving this focus to
6325     * another view.
6326     */
6327    void clearAccessibilityFocusNoCallbacks() {
6328        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6329            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6330            setAccessibilityCursorPosition(ACCESSIBILITY_CURSOR_POSITION_UNDEFINED);
6331            invalidate();
6332        }
6333    }
6334
6335    /**
6336     * Call this to try to give focus to a specific view or to one of its
6337     * descendants.
6338     *
6339     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6340     * false), or if it is focusable and it is not focusable in touch mode
6341     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6342     *
6343     * See also {@link #focusSearch(int)}, which is what you call to say that you
6344     * have focus, and you want your parent to look for the next one.
6345     *
6346     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6347     * {@link #FOCUS_DOWN} and <code>null</code>.
6348     *
6349     * @return Whether this view or one of its descendants actually took focus.
6350     */
6351    public final boolean requestFocus() {
6352        return requestFocus(View.FOCUS_DOWN);
6353    }
6354
6355    /**
6356     * Call this to try to give focus to a specific view or to one of its
6357     * descendants and give it a hint about what direction focus is heading.
6358     *
6359     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6360     * false), or if it is focusable and it is not focusable in touch mode
6361     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6362     *
6363     * See also {@link #focusSearch(int)}, which is what you call to say that you
6364     * have focus, and you want your parent to look for the next one.
6365     *
6366     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6367     * <code>null</code> set for the previously focused rectangle.
6368     *
6369     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6370     * @return Whether this view or one of its descendants actually took focus.
6371     */
6372    public final boolean requestFocus(int direction) {
6373        return requestFocus(direction, null);
6374    }
6375
6376    /**
6377     * Call this to try to give focus to a specific view or to one of its descendants
6378     * and give it hints about the direction and a specific rectangle that the focus
6379     * is coming from.  The rectangle can help give larger views a finer grained hint
6380     * about where focus is coming from, and therefore, where to show selection, or
6381     * forward focus change internally.
6382     *
6383     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6384     * false), or if it is focusable and it is not focusable in touch mode
6385     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6386     *
6387     * A View will not take focus if it is not visible.
6388     *
6389     * A View will not take focus if one of its parents has
6390     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6391     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6392     *
6393     * See also {@link #focusSearch(int)}, which is what you call to say that you
6394     * have focus, and you want your parent to look for the next one.
6395     *
6396     * You may wish to override this method if your custom {@link View} has an internal
6397     * {@link View} that it wishes to forward the request to.
6398     *
6399     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6400     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6401     *        to give a finer grained hint about where focus is coming from.  May be null
6402     *        if there is no hint.
6403     * @return Whether this view or one of its descendants actually took focus.
6404     */
6405    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6406        return requestFocusNoSearch(direction, previouslyFocusedRect);
6407    }
6408
6409    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6410        // need to be focusable
6411        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6412                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6413            return false;
6414        }
6415
6416        // need to be focusable in touch mode if in touch mode
6417        if (isInTouchMode() &&
6418            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6419               return false;
6420        }
6421
6422        // need to not have any parents blocking us
6423        if (hasAncestorThatBlocksDescendantFocus()) {
6424            return false;
6425        }
6426
6427        handleFocusGainInternal(direction, previouslyFocusedRect);
6428        return true;
6429    }
6430
6431    /**
6432     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6433     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6434     * touch mode to request focus when they are touched.
6435     *
6436     * @return Whether this view or one of its descendants actually took focus.
6437     *
6438     * @see #isInTouchMode()
6439     *
6440     */
6441    public final boolean requestFocusFromTouch() {
6442        // Leave touch mode if we need to
6443        if (isInTouchMode()) {
6444            ViewRootImpl viewRoot = getViewRootImpl();
6445            if (viewRoot != null) {
6446                viewRoot.ensureTouchMode(false);
6447            }
6448        }
6449        return requestFocus(View.FOCUS_DOWN);
6450    }
6451
6452    /**
6453     * @return Whether any ancestor of this view blocks descendant focus.
6454     */
6455    private boolean hasAncestorThatBlocksDescendantFocus() {
6456        ViewParent ancestor = mParent;
6457        while (ancestor instanceof ViewGroup) {
6458            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6459            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6460                return true;
6461            } else {
6462                ancestor = vgAncestor.getParent();
6463            }
6464        }
6465        return false;
6466    }
6467
6468    /**
6469     * Gets the mode for determining whether this View is important for accessibility
6470     * which is if it fires accessibility events and if it is reported to
6471     * accessibility services that query the screen.
6472     *
6473     * @return The mode for determining whether a View is important for accessibility.
6474     *
6475     * @attr ref android.R.styleable#View_importantForAccessibility
6476     *
6477     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6478     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6479     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6480     */
6481    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6482            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6483            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6484            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6485        })
6486    public int getImportantForAccessibility() {
6487        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6488                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6489    }
6490
6491    /**
6492     * Sets how to determine whether this view is important for accessibility
6493     * which is if it fires accessibility events and if it is reported to
6494     * accessibility services that query the screen.
6495     *
6496     * @param mode How to determine whether this view is important for accessibility.
6497     *
6498     * @attr ref android.R.styleable#View_importantForAccessibility
6499     *
6500     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6501     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6502     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6503     */
6504    public void setImportantForAccessibility(int mode) {
6505        if (mode != getImportantForAccessibility()) {
6506            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6507            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6508                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6509            notifyAccessibilityStateChanged();
6510        }
6511    }
6512
6513    /**
6514     * Gets whether this view should be exposed for accessibility.
6515     *
6516     * @return Whether the view is exposed for accessibility.
6517     *
6518     * @hide
6519     */
6520    public boolean isImportantForAccessibility() {
6521        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6522                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6523        switch (mode) {
6524            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6525                return true;
6526            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6527                return false;
6528            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6529                return isActionableForAccessibility() || hasListenersForAccessibility();
6530            default:
6531                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6532                        + mode);
6533        }
6534    }
6535
6536    /**
6537     * Gets the mode for determining whether this View can take accessibility focus.
6538     *
6539     * @return The mode for determining whether a View can take accessibility focus.
6540     *
6541     * @attr ref android.R.styleable#View_accessibilityFocusable
6542     *
6543     * @see #ACCESSIBILITY_FOCUSABLE_YES
6544     * @see #ACCESSIBILITY_FOCUSABLE_NO
6545     * @see #ACCESSIBILITY_FOCUSABLE_AUTO
6546     *
6547     * @hide
6548     */
6549    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6550            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_AUTO, to = "auto"),
6551            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_YES, to = "yes"),
6552            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_NO, to = "no")
6553        })
6554    public int getAccessibilityFocusable() {
6555        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSABLE_MASK) >>> ACCESSIBILITY_FOCUSABLE_SHIFT;
6556    }
6557
6558    /**
6559     * Sets how to determine whether this view can take accessibility focus.
6560     *
6561     * @param mode How to determine whether this view can take accessibility focus.
6562     *
6563     * @attr ref android.R.styleable#View_accessibilityFocusable
6564     *
6565     * @see #ACCESSIBILITY_FOCUSABLE_YES
6566     * @see #ACCESSIBILITY_FOCUSABLE_NO
6567     * @see #ACCESSIBILITY_FOCUSABLE_AUTO
6568     *
6569     * @hide
6570     */
6571    public void setAccessibilityFocusable(int mode) {
6572        if (mode != getAccessibilityFocusable()) {
6573            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSABLE_MASK;
6574            mPrivateFlags2 |= (mode << ACCESSIBILITY_FOCUSABLE_SHIFT)
6575                    & ACCESSIBILITY_FOCUSABLE_MASK;
6576            notifyAccessibilityStateChanged();
6577        }
6578    }
6579
6580    /**
6581     * Gets whether this view can take accessibility focus.
6582     *
6583     * @return Whether the view can take accessibility focus.
6584     *
6585     * @hide
6586     */
6587    public boolean isAccessibilityFocusable() {
6588        final int mode = (mPrivateFlags2 & ACCESSIBILITY_FOCUSABLE_MASK)
6589                >>> ACCESSIBILITY_FOCUSABLE_SHIFT;
6590        switch (mode) {
6591            case ACCESSIBILITY_FOCUSABLE_YES:
6592                return true;
6593            case ACCESSIBILITY_FOCUSABLE_NO:
6594                return false;
6595            case ACCESSIBILITY_FOCUSABLE_AUTO:
6596                return canTakeAccessibilityFocusFromHover()
6597                        || getAccessibilityNodeProvider() != null;
6598            default:
6599                throw new IllegalArgumentException("Unknow accessibility focusable mode: " + mode);
6600        }
6601    }
6602
6603    /**
6604     * Gets the parent for accessibility purposes. Note that the parent for
6605     * accessibility is not necessary the immediate parent. It is the first
6606     * predecessor that is important for accessibility.
6607     *
6608     * @return The parent for accessibility purposes.
6609     */
6610    public ViewParent getParentForAccessibility() {
6611        if (mParent instanceof View) {
6612            View parentView = (View) mParent;
6613            if (parentView.includeForAccessibility()) {
6614                return mParent;
6615            } else {
6616                return mParent.getParentForAccessibility();
6617            }
6618        }
6619        return null;
6620    }
6621
6622    /**
6623     * Adds the children of a given View for accessibility. Since some Views are
6624     * not important for accessibility the children for accessibility are not
6625     * necessarily direct children of the riew, rather they are the first level of
6626     * descendants important for accessibility.
6627     *
6628     * @param children The list of children for accessibility.
6629     */
6630    public void addChildrenForAccessibility(ArrayList<View> children) {
6631        if (includeForAccessibility()) {
6632            children.add(this);
6633        }
6634    }
6635
6636    /**
6637     * Whether to regard this view for accessibility. A view is regarded for
6638     * accessibility if it is important for accessibility or the querying
6639     * accessibility service has explicitly requested that view not
6640     * important for accessibility are regarded.
6641     *
6642     * @return Whether to regard the view for accessibility.
6643     *
6644     * @hide
6645     */
6646    public boolean includeForAccessibility() {
6647        if (mAttachInfo != null) {
6648            if (!mAttachInfo.mIncludeNotImportantViews) {
6649                return isImportantForAccessibility();
6650            }
6651            return true;
6652        }
6653        return false;
6654    }
6655
6656    /**
6657     * Returns whether the View is considered actionable from
6658     * accessibility perspective. Such view are important for
6659     * accessiiblity.
6660     *
6661     * @return True if the view is actionable for accessibility.
6662     *
6663     * @hide
6664     */
6665    public boolean isActionableForAccessibility() {
6666        return (isClickable() || isLongClickable() || isFocusable());
6667    }
6668
6669    /**
6670     * Returns whether the View has registered callbacks wich makes it
6671     * important for accessiiblity.
6672     *
6673     * @return True if the view is actionable for accessibility.
6674     */
6675    private boolean hasListenersForAccessibility() {
6676        ListenerInfo info = getListenerInfo();
6677        return mTouchDelegate != null || info.mOnKeyListener != null
6678                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6679                || info.mOnHoverListener != null || info.mOnDragListener != null;
6680    }
6681
6682    /**
6683     * Notifies accessibility services that some view's important for
6684     * accessibility state has changed. Note that such notifications
6685     * are made at most once every
6686     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6687     * to avoid unnecessary load to the system. Also once a view has
6688     * made a notifucation this method is a NOP until the notification has
6689     * been sent to clients.
6690     *
6691     * @hide
6692     *
6693     * TODO: Makse sure this method is called for any view state change
6694     *       that is interesting for accessilility purposes.
6695     */
6696    public void notifyAccessibilityStateChanged() {
6697        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6698            return;
6699        }
6700        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6701            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6702            if (mParent != null) {
6703                mParent.childAccessibilityStateChanged(this);
6704            }
6705        }
6706    }
6707
6708    /**
6709     * Reset the state indicating the this view has requested clients
6710     * interested in its accessiblity state to be notified.
6711     *
6712     * @hide
6713     */
6714    public void resetAccessibilityStateChanged() {
6715        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6716    }
6717
6718    /**
6719     * Performs the specified accessibility action on the view. For
6720     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6721    * <p>
6722    * If an {@link AccessibilityDelegate} has been specified via calling
6723    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6724    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6725    * is responsible for handling this call.
6726    * </p>
6727     *
6728     * @param action The action to perform.
6729     * @param arguments Optional action arguments.
6730     * @return Whether the action was performed.
6731     */
6732    public boolean performAccessibilityAction(int action, Bundle arguments) {
6733      if (mAccessibilityDelegate != null) {
6734          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6735      } else {
6736          return performAccessibilityActionInternal(action, arguments);
6737      }
6738    }
6739
6740   /**
6741    * @see #performAccessibilityAction(int, Bundle)
6742    *
6743    * Note: Called from the default {@link AccessibilityDelegate}.
6744    */
6745    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6746        switch (action) {
6747            case AccessibilityNodeInfo.ACTION_CLICK: {
6748                if (isClickable()) {
6749                    return performClick();
6750                }
6751            } break;
6752            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6753                if (isLongClickable()) {
6754                    return performLongClick();
6755                }
6756            } break;
6757            case AccessibilityNodeInfo.ACTION_FOCUS: {
6758                if (!hasFocus()) {
6759                    // Get out of touch mode since accessibility
6760                    // wants to move focus around.
6761                    getViewRootImpl().ensureTouchMode(false);
6762                    return requestFocus();
6763                }
6764            } break;
6765            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6766                if (hasFocus()) {
6767                    clearFocus();
6768                    return !isFocused();
6769                }
6770            } break;
6771            case AccessibilityNodeInfo.ACTION_SELECT: {
6772                if (!isSelected()) {
6773                    setSelected(true);
6774                    return isSelected();
6775                }
6776            } break;
6777            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6778                if (isSelected()) {
6779                    setSelected(false);
6780                    return !isSelected();
6781                }
6782            } break;
6783            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6784                final int mode = getAccessibilityFocusable();
6785                if (!isAccessibilityFocused()
6786                        && (mode == ACCESSIBILITY_FOCUSABLE_YES
6787                                || mode == ACCESSIBILITY_FOCUSABLE_AUTO)) {
6788                    return requestAccessibilityFocus();
6789                }
6790            } break;
6791            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6792                if (isAccessibilityFocused()) {
6793                    clearAccessibilityFocus();
6794                    return true;
6795                }
6796            } break;
6797            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6798                if (arguments != null) {
6799                    final int granularity = arguments.getInt(
6800                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6801                    return nextAtGranularity(granularity);
6802                }
6803            } break;
6804            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6805                if (arguments != null) {
6806                    final int granularity = arguments.getInt(
6807                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6808                    return previousAtGranularity(granularity);
6809                }
6810            } break;
6811        }
6812        return false;
6813    }
6814
6815    private boolean nextAtGranularity(int granularity) {
6816        CharSequence text = getIterableTextForAccessibility();
6817        if (text == null || text.length() == 0) {
6818            return false;
6819        }
6820        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6821        if (iterator == null) {
6822            return false;
6823        }
6824        final int current = getAccessibilityCursorPosition();
6825        final int[] range = iterator.following(current);
6826        if (range == null) {
6827            return false;
6828        }
6829        final int start = range[0];
6830        final int end = range[1];
6831        setAccessibilityCursorPosition(end);
6832        sendViewTextTraversedAtGranularityEvent(
6833                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6834                granularity, start, end);
6835        return true;
6836    }
6837
6838    private boolean previousAtGranularity(int granularity) {
6839        CharSequence text = getIterableTextForAccessibility();
6840        if (text == null || text.length() == 0) {
6841            return false;
6842        }
6843        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6844        if (iterator == null) {
6845            return false;
6846        }
6847        int current = getAccessibilityCursorPosition();
6848        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6849            current = text.length();
6850        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6851            // When traversing by character we always put the cursor after the character
6852            // to ease edit and have to compensate before asking the for previous segment.
6853            current--;
6854        }
6855        final int[] range = iterator.preceding(current);
6856        if (range == null) {
6857            return false;
6858        }
6859        final int start = range[0];
6860        final int end = range[1];
6861        // Always put the cursor after the character to ease edit.
6862        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6863            setAccessibilityCursorPosition(end);
6864        } else {
6865            setAccessibilityCursorPosition(start);
6866        }
6867        sendViewTextTraversedAtGranularityEvent(
6868                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6869                granularity, start, end);
6870        return true;
6871    }
6872
6873    /**
6874     * Gets the text reported for accessibility purposes.
6875     *
6876     * @return The accessibility text.
6877     *
6878     * @hide
6879     */
6880    public CharSequence getIterableTextForAccessibility() {
6881        return mContentDescription;
6882    }
6883
6884    /**
6885     * @hide
6886     */
6887    public int getAccessibilityCursorPosition() {
6888        return mAccessibilityCursorPosition;
6889    }
6890
6891    /**
6892     * @hide
6893     */
6894    public void setAccessibilityCursorPosition(int position) {
6895        mAccessibilityCursorPosition = position;
6896    }
6897
6898    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6899            int fromIndex, int toIndex) {
6900        if (mParent == null) {
6901            return;
6902        }
6903        AccessibilityEvent event = AccessibilityEvent.obtain(
6904                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6905        onInitializeAccessibilityEvent(event);
6906        onPopulateAccessibilityEvent(event);
6907        event.setFromIndex(fromIndex);
6908        event.setToIndex(toIndex);
6909        event.setAction(action);
6910        event.setMovementGranularity(granularity);
6911        mParent.requestSendAccessibilityEvent(this, event);
6912    }
6913
6914    /**
6915     * @hide
6916     */
6917    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6918        switch (granularity) {
6919            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6920                CharSequence text = getIterableTextForAccessibility();
6921                if (text != null && text.length() > 0) {
6922                    CharacterTextSegmentIterator iterator =
6923                        CharacterTextSegmentIterator.getInstance(mContext);
6924                    iterator.initialize(text.toString());
6925                    return iterator;
6926                }
6927            } break;
6928            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6929                CharSequence text = getIterableTextForAccessibility();
6930                if (text != null && text.length() > 0) {
6931                    WordTextSegmentIterator iterator =
6932                        WordTextSegmentIterator.getInstance(mContext);
6933                    iterator.initialize(text.toString());
6934                    return iterator;
6935                }
6936            } break;
6937            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6938                CharSequence text = getIterableTextForAccessibility();
6939                if (text != null && text.length() > 0) {
6940                    ParagraphTextSegmentIterator iterator =
6941                        ParagraphTextSegmentIterator.getInstance();
6942                    iterator.initialize(text.toString());
6943                    return iterator;
6944                }
6945            } break;
6946        }
6947        return null;
6948    }
6949
6950    /**
6951     * @hide
6952     */
6953    public void dispatchStartTemporaryDetach() {
6954        clearAccessibilityFocus();
6955        clearDisplayList();
6956
6957        onStartTemporaryDetach();
6958    }
6959
6960    /**
6961     * This is called when a container is going to temporarily detach a child, with
6962     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6963     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6964     * {@link #onDetachedFromWindow()} when the container is done.
6965     */
6966    public void onStartTemporaryDetach() {
6967        removeUnsetPressCallback();
6968        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6969    }
6970
6971    /**
6972     * @hide
6973     */
6974    public void dispatchFinishTemporaryDetach() {
6975        onFinishTemporaryDetach();
6976    }
6977
6978    /**
6979     * Called after {@link #onStartTemporaryDetach} when the container is done
6980     * changing the view.
6981     */
6982    public void onFinishTemporaryDetach() {
6983    }
6984
6985    /**
6986     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6987     * for this view's window.  Returns null if the view is not currently attached
6988     * to the window.  Normally you will not need to use this directly, but
6989     * just use the standard high-level event callbacks like
6990     * {@link #onKeyDown(int, KeyEvent)}.
6991     */
6992    public KeyEvent.DispatcherState getKeyDispatcherState() {
6993        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6994    }
6995
6996    /**
6997     * Dispatch a key event before it is processed by any input method
6998     * associated with the view hierarchy.  This can be used to intercept
6999     * key events in special situations before the IME consumes them; a
7000     * typical example would be handling the BACK key to update the application's
7001     * UI instead of allowing the IME to see it and close itself.
7002     *
7003     * @param event The key event to be dispatched.
7004     * @return True if the event was handled, false otherwise.
7005     */
7006    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7007        return onKeyPreIme(event.getKeyCode(), event);
7008    }
7009
7010    /**
7011     * Dispatch a key event to the next view on the focus path. This path runs
7012     * from the top of the view tree down to the currently focused view. If this
7013     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7014     * the next node down the focus path. This method also fires any key
7015     * listeners.
7016     *
7017     * @param event The key event to be dispatched.
7018     * @return True if the event was handled, false otherwise.
7019     */
7020    public boolean dispatchKeyEvent(KeyEvent event) {
7021        if (mInputEventConsistencyVerifier != null) {
7022            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7023        }
7024
7025        // Give any attached key listener a first crack at the event.
7026        //noinspection SimplifiableIfStatement
7027        ListenerInfo li = mListenerInfo;
7028        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7029                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7030            return true;
7031        }
7032
7033        if (event.dispatch(this, mAttachInfo != null
7034                ? mAttachInfo.mKeyDispatchState : null, this)) {
7035            return true;
7036        }
7037
7038        if (mInputEventConsistencyVerifier != null) {
7039            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7040        }
7041        return false;
7042    }
7043
7044    /**
7045     * Dispatches a key shortcut event.
7046     *
7047     * @param event The key event to be dispatched.
7048     * @return True if the event was handled by the view, false otherwise.
7049     */
7050    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7051        return onKeyShortcut(event.getKeyCode(), event);
7052    }
7053
7054    /**
7055     * Pass the touch screen motion event down to the target view, or this
7056     * view if it is the target.
7057     *
7058     * @param event The motion event to be dispatched.
7059     * @return True if the event was handled by the view, false otherwise.
7060     */
7061    public boolean dispatchTouchEvent(MotionEvent event) {
7062        if (mInputEventConsistencyVerifier != null) {
7063            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7064        }
7065
7066        if (onFilterTouchEventForSecurity(event)) {
7067            //noinspection SimplifiableIfStatement
7068            ListenerInfo li = mListenerInfo;
7069            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7070                    && li.mOnTouchListener.onTouch(this, event)) {
7071                return true;
7072            }
7073
7074            if (onTouchEvent(event)) {
7075                return true;
7076            }
7077        }
7078
7079        if (mInputEventConsistencyVerifier != null) {
7080            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7081        }
7082        return false;
7083    }
7084
7085    /**
7086     * Filter the touch event to apply security policies.
7087     *
7088     * @param event The motion event to be filtered.
7089     * @return True if the event should be dispatched, false if the event should be dropped.
7090     *
7091     * @see #getFilterTouchesWhenObscured
7092     */
7093    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7094        //noinspection RedundantIfStatement
7095        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7096                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7097            // Window is obscured, drop this touch.
7098            return false;
7099        }
7100        return true;
7101    }
7102
7103    /**
7104     * Pass a trackball motion event down to the focused view.
7105     *
7106     * @param event The motion event to be dispatched.
7107     * @return True if the event was handled by the view, false otherwise.
7108     */
7109    public boolean dispatchTrackballEvent(MotionEvent event) {
7110        if (mInputEventConsistencyVerifier != null) {
7111            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7112        }
7113
7114        return onTrackballEvent(event);
7115    }
7116
7117    /**
7118     * Dispatch a generic motion event.
7119     * <p>
7120     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7121     * are delivered to the view under the pointer.  All other generic motion events are
7122     * delivered to the focused view.  Hover events are handled specially and are delivered
7123     * to {@link #onHoverEvent(MotionEvent)}.
7124     * </p>
7125     *
7126     * @param event The motion event to be dispatched.
7127     * @return True if the event was handled by the view, false otherwise.
7128     */
7129    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7130        if (mInputEventConsistencyVerifier != null) {
7131            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7132        }
7133
7134        final int source = event.getSource();
7135        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7136            final int action = event.getAction();
7137            if (action == MotionEvent.ACTION_HOVER_ENTER
7138                    || action == MotionEvent.ACTION_HOVER_MOVE
7139                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7140                if (dispatchHoverEvent(event)) {
7141                    return true;
7142                }
7143            } else if (dispatchGenericPointerEvent(event)) {
7144                return true;
7145            }
7146        } else if (dispatchGenericFocusedEvent(event)) {
7147            return true;
7148        }
7149
7150        if (dispatchGenericMotionEventInternal(event)) {
7151            return true;
7152        }
7153
7154        if (mInputEventConsistencyVerifier != null) {
7155            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7156        }
7157        return false;
7158    }
7159
7160    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7161        //noinspection SimplifiableIfStatement
7162        ListenerInfo li = mListenerInfo;
7163        if (li != null && li.mOnGenericMotionListener != null
7164                && (mViewFlags & ENABLED_MASK) == ENABLED
7165                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7166            return true;
7167        }
7168
7169        if (onGenericMotionEvent(event)) {
7170            return true;
7171        }
7172
7173        if (mInputEventConsistencyVerifier != null) {
7174            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7175        }
7176        return false;
7177    }
7178
7179    /**
7180     * Dispatch a hover event.
7181     * <p>
7182     * Do not call this method directly.
7183     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7184     * </p>
7185     *
7186     * @param event The motion event to be dispatched.
7187     * @return True if the event was handled by the view, false otherwise.
7188     */
7189    protected boolean dispatchHoverEvent(MotionEvent event) {
7190        //noinspection SimplifiableIfStatement
7191        ListenerInfo li = mListenerInfo;
7192        if (li != null && li.mOnHoverListener != null
7193                && (mViewFlags & ENABLED_MASK) == ENABLED
7194                && li.mOnHoverListener.onHover(this, event)) {
7195            return true;
7196        }
7197
7198        return onHoverEvent(event);
7199    }
7200
7201    /**
7202     * Returns true if the view has a child to which it has recently sent
7203     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7204     * it does not have a hovered child, then it must be the innermost hovered view.
7205     * @hide
7206     */
7207    protected boolean hasHoveredChild() {
7208        return false;
7209    }
7210
7211    /**
7212     * Dispatch a generic motion event to the view under the first pointer.
7213     * <p>
7214     * Do not call this method directly.
7215     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7216     * </p>
7217     *
7218     * @param event The motion event to be dispatched.
7219     * @return True if the event was handled by the view, false otherwise.
7220     */
7221    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7222        return false;
7223    }
7224
7225    /**
7226     * Dispatch a generic motion event to the currently focused view.
7227     * <p>
7228     * Do not call this method directly.
7229     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7230     * </p>
7231     *
7232     * @param event The motion event to be dispatched.
7233     * @return True if the event was handled by the view, false otherwise.
7234     */
7235    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7236        return false;
7237    }
7238
7239    /**
7240     * Dispatch a pointer event.
7241     * <p>
7242     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7243     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7244     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7245     * and should not be expected to handle other pointing device features.
7246     * </p>
7247     *
7248     * @param event The motion event to be dispatched.
7249     * @return True if the event was handled by the view, false otherwise.
7250     * @hide
7251     */
7252    public final boolean dispatchPointerEvent(MotionEvent event) {
7253        if (event.isTouchEvent()) {
7254            return dispatchTouchEvent(event);
7255        } else {
7256            return dispatchGenericMotionEvent(event);
7257        }
7258    }
7259
7260    /**
7261     * Called when the window containing this view gains or loses window focus.
7262     * ViewGroups should override to route to their children.
7263     *
7264     * @param hasFocus True if the window containing this view now has focus,
7265     *        false otherwise.
7266     */
7267    public void dispatchWindowFocusChanged(boolean hasFocus) {
7268        onWindowFocusChanged(hasFocus);
7269    }
7270
7271    /**
7272     * Called when the window containing this view gains or loses focus.  Note
7273     * that this is separate from view focus: to receive key events, both
7274     * your view and its window must have focus.  If a window is displayed
7275     * on top of yours that takes input focus, then your own window will lose
7276     * focus but the view focus will remain unchanged.
7277     *
7278     * @param hasWindowFocus True if the window containing this view now has
7279     *        focus, false otherwise.
7280     */
7281    public void onWindowFocusChanged(boolean hasWindowFocus) {
7282        InputMethodManager imm = InputMethodManager.peekInstance();
7283        if (!hasWindowFocus) {
7284            if (isPressed()) {
7285                setPressed(false);
7286            }
7287            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7288                imm.focusOut(this);
7289            }
7290            removeLongPressCallback();
7291            removeTapCallback();
7292            onFocusLost();
7293        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7294            imm.focusIn(this);
7295        }
7296        refreshDrawableState();
7297    }
7298
7299    /**
7300     * Returns true if this view is in a window that currently has window focus.
7301     * Note that this is not the same as the view itself having focus.
7302     *
7303     * @return True if this view is in a window that currently has window focus.
7304     */
7305    public boolean hasWindowFocus() {
7306        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7307    }
7308
7309    /**
7310     * Dispatch a view visibility change down the view hierarchy.
7311     * ViewGroups should override to route to their children.
7312     * @param changedView The view whose visibility changed. Could be 'this' or
7313     * an ancestor view.
7314     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7315     * {@link #INVISIBLE} or {@link #GONE}.
7316     */
7317    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7318        onVisibilityChanged(changedView, visibility);
7319    }
7320
7321    /**
7322     * Called when the visibility of the view or an ancestor of the view is changed.
7323     * @param changedView The view whose visibility changed. Could be 'this' or
7324     * an ancestor view.
7325     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7326     * {@link #INVISIBLE} or {@link #GONE}.
7327     */
7328    protected void onVisibilityChanged(View changedView, int visibility) {
7329        if (visibility == VISIBLE) {
7330            if (mAttachInfo != null) {
7331                initialAwakenScrollBars();
7332            } else {
7333                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7334            }
7335        }
7336    }
7337
7338    /**
7339     * Dispatch a hint about whether this view is displayed. For instance, when
7340     * a View moves out of the screen, it might receives a display hint indicating
7341     * the view is not displayed. Applications should not <em>rely</em> on this hint
7342     * as there is no guarantee that they will receive one.
7343     *
7344     * @param hint A hint about whether or not this view is displayed:
7345     * {@link #VISIBLE} or {@link #INVISIBLE}.
7346     */
7347    public void dispatchDisplayHint(int hint) {
7348        onDisplayHint(hint);
7349    }
7350
7351    /**
7352     * Gives this view a hint about whether is displayed or not. For instance, when
7353     * a View moves out of the screen, it might receives a display hint indicating
7354     * the view is not displayed. Applications should not <em>rely</em> on this hint
7355     * as there is no guarantee that they will receive one.
7356     *
7357     * @param hint A hint about whether or not this view is displayed:
7358     * {@link #VISIBLE} or {@link #INVISIBLE}.
7359     */
7360    protected void onDisplayHint(int hint) {
7361    }
7362
7363    /**
7364     * Dispatch a window visibility change down the view hierarchy.
7365     * ViewGroups should override to route to their children.
7366     *
7367     * @param visibility The new visibility of the window.
7368     *
7369     * @see #onWindowVisibilityChanged(int)
7370     */
7371    public void dispatchWindowVisibilityChanged(int visibility) {
7372        onWindowVisibilityChanged(visibility);
7373    }
7374
7375    /**
7376     * Called when the window containing has change its visibility
7377     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7378     * that this tells you whether or not your window is being made visible
7379     * to the window manager; this does <em>not</em> tell you whether or not
7380     * your window is obscured by other windows on the screen, even if it
7381     * is itself visible.
7382     *
7383     * @param visibility The new visibility of the window.
7384     */
7385    protected void onWindowVisibilityChanged(int visibility) {
7386        if (visibility == VISIBLE) {
7387            initialAwakenScrollBars();
7388        }
7389    }
7390
7391    /**
7392     * Returns the current visibility of the window this view is attached to
7393     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7394     *
7395     * @return Returns the current visibility of the view's window.
7396     */
7397    public int getWindowVisibility() {
7398        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7399    }
7400
7401    /**
7402     * Retrieve the overall visible display size in which the window this view is
7403     * attached to has been positioned in.  This takes into account screen
7404     * decorations above the window, for both cases where the window itself
7405     * is being position inside of them or the window is being placed under
7406     * then and covered insets are used for the window to position its content
7407     * inside.  In effect, this tells you the available area where content can
7408     * be placed and remain visible to users.
7409     *
7410     * <p>This function requires an IPC back to the window manager to retrieve
7411     * the requested information, so should not be used in performance critical
7412     * code like drawing.
7413     *
7414     * @param outRect Filled in with the visible display frame.  If the view
7415     * is not attached to a window, this is simply the raw display size.
7416     */
7417    public void getWindowVisibleDisplayFrame(Rect outRect) {
7418        if (mAttachInfo != null) {
7419            try {
7420                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7421            } catch (RemoteException e) {
7422                return;
7423            }
7424            // XXX This is really broken, and probably all needs to be done
7425            // in the window manager, and we need to know more about whether
7426            // we want the area behind or in front of the IME.
7427            final Rect insets = mAttachInfo.mVisibleInsets;
7428            outRect.left += insets.left;
7429            outRect.top += insets.top;
7430            outRect.right -= insets.right;
7431            outRect.bottom -= insets.bottom;
7432            return;
7433        }
7434        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7435        d.getRectSize(outRect);
7436    }
7437
7438    /**
7439     * Dispatch a notification about a resource configuration change down
7440     * the view hierarchy.
7441     * ViewGroups should override to route to their children.
7442     *
7443     * @param newConfig The new resource configuration.
7444     *
7445     * @see #onConfigurationChanged(android.content.res.Configuration)
7446     */
7447    public void dispatchConfigurationChanged(Configuration newConfig) {
7448        onConfigurationChanged(newConfig);
7449    }
7450
7451    /**
7452     * Called when the current configuration of the resources being used
7453     * by the application have changed.  You can use this to decide when
7454     * to reload resources that can changed based on orientation and other
7455     * configuration characterstics.  You only need to use this if you are
7456     * not relying on the normal {@link android.app.Activity} mechanism of
7457     * recreating the activity instance upon a configuration change.
7458     *
7459     * @param newConfig The new resource configuration.
7460     */
7461    protected void onConfigurationChanged(Configuration newConfig) {
7462    }
7463
7464    /**
7465     * Private function to aggregate all per-view attributes in to the view
7466     * root.
7467     */
7468    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7469        performCollectViewAttributes(attachInfo, visibility);
7470    }
7471
7472    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7473        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7474            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7475                attachInfo.mKeepScreenOn = true;
7476            }
7477            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7478            ListenerInfo li = mListenerInfo;
7479            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7480                attachInfo.mHasSystemUiListeners = true;
7481            }
7482        }
7483    }
7484
7485    void needGlobalAttributesUpdate(boolean force) {
7486        final AttachInfo ai = mAttachInfo;
7487        if (ai != null) {
7488            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7489                    || ai.mHasSystemUiListeners) {
7490                ai.mRecomputeGlobalAttributes = true;
7491            }
7492        }
7493    }
7494
7495    /**
7496     * Returns whether the device is currently in touch mode.  Touch mode is entered
7497     * once the user begins interacting with the device by touch, and affects various
7498     * things like whether focus is always visible to the user.
7499     *
7500     * @return Whether the device is in touch mode.
7501     */
7502    @ViewDebug.ExportedProperty
7503    public boolean isInTouchMode() {
7504        if (mAttachInfo != null) {
7505            return mAttachInfo.mInTouchMode;
7506        } else {
7507            return ViewRootImpl.isInTouchMode();
7508        }
7509    }
7510
7511    /**
7512     * Returns the context the view is running in, through which it can
7513     * access the current theme, resources, etc.
7514     *
7515     * @return The view's Context.
7516     */
7517    @ViewDebug.CapturedViewProperty
7518    public final Context getContext() {
7519        return mContext;
7520    }
7521
7522    /**
7523     * Handle a key event before it is processed by any input method
7524     * associated with the view hierarchy.  This can be used to intercept
7525     * key events in special situations before the IME consumes them; a
7526     * typical example would be handling the BACK key to update the application's
7527     * UI instead of allowing the IME to see it and close itself.
7528     *
7529     * @param keyCode The value in event.getKeyCode().
7530     * @param event Description of the key event.
7531     * @return If you handled the event, return true. If you want to allow the
7532     *         event to be handled by the next receiver, return false.
7533     */
7534    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7535        return false;
7536    }
7537
7538    /**
7539     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7540     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7541     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7542     * is released, if the view is enabled and clickable.
7543     *
7544     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7545     * although some may elect to do so in some situations. Do not rely on this to
7546     * catch software key presses.
7547     *
7548     * @param keyCode A key code that represents the button pressed, from
7549     *                {@link android.view.KeyEvent}.
7550     * @param event   The KeyEvent object that defines the button action.
7551     */
7552    public boolean onKeyDown(int keyCode, KeyEvent event) {
7553        boolean result = false;
7554
7555        switch (keyCode) {
7556            case KeyEvent.KEYCODE_DPAD_CENTER:
7557            case KeyEvent.KEYCODE_ENTER: {
7558                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7559                    return true;
7560                }
7561                // Long clickable items don't necessarily have to be clickable
7562                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7563                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7564                        (event.getRepeatCount() == 0)) {
7565                    setPressed(true);
7566                    checkForLongClick(0);
7567                    return true;
7568                }
7569                break;
7570            }
7571        }
7572        return result;
7573    }
7574
7575    /**
7576     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7577     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7578     * the event).
7579     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7580     * although some may elect to do so in some situations. Do not rely on this to
7581     * catch software key presses.
7582     */
7583    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7584        return false;
7585    }
7586
7587    /**
7588     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7589     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7590     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7591     * {@link KeyEvent#KEYCODE_ENTER} is released.
7592     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7593     * although some may elect to do so in some situations. Do not rely on this to
7594     * catch software key presses.
7595     *
7596     * @param keyCode A key code that represents the button pressed, from
7597     *                {@link android.view.KeyEvent}.
7598     * @param event   The KeyEvent object that defines the button action.
7599     */
7600    public boolean onKeyUp(int keyCode, KeyEvent event) {
7601        boolean result = false;
7602
7603        switch (keyCode) {
7604            case KeyEvent.KEYCODE_DPAD_CENTER:
7605            case KeyEvent.KEYCODE_ENTER: {
7606                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7607                    return true;
7608                }
7609                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7610                    setPressed(false);
7611
7612                    if (!mHasPerformedLongPress) {
7613                        // This is a tap, so remove the longpress check
7614                        removeLongPressCallback();
7615
7616                        result = performClick();
7617                    }
7618                }
7619                break;
7620            }
7621        }
7622        return result;
7623    }
7624
7625    /**
7626     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7627     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7628     * the event).
7629     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7630     * although some may elect to do so in some situations. Do not rely on this to
7631     * catch software key presses.
7632     *
7633     * @param keyCode     A key code that represents the button pressed, from
7634     *                    {@link android.view.KeyEvent}.
7635     * @param repeatCount The number of times the action was made.
7636     * @param event       The KeyEvent object that defines the button action.
7637     */
7638    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7639        return false;
7640    }
7641
7642    /**
7643     * Called on the focused view when a key shortcut event is not handled.
7644     * Override this method to implement local key shortcuts for the View.
7645     * Key shortcuts can also be implemented by setting the
7646     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7647     *
7648     * @param keyCode The value in event.getKeyCode().
7649     * @param event Description of the key event.
7650     * @return If you handled the event, return true. If you want to allow the
7651     *         event to be handled by the next receiver, return false.
7652     */
7653    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7654        return false;
7655    }
7656
7657    /**
7658     * Check whether the called view is a text editor, in which case it
7659     * would make sense to automatically display a soft input window for
7660     * it.  Subclasses should override this if they implement
7661     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7662     * a call on that method would return a non-null InputConnection, and
7663     * they are really a first-class editor that the user would normally
7664     * start typing on when the go into a window containing your view.
7665     *
7666     * <p>The default implementation always returns false.  This does
7667     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7668     * will not be called or the user can not otherwise perform edits on your
7669     * view; it is just a hint to the system that this is not the primary
7670     * purpose of this view.
7671     *
7672     * @return Returns true if this view is a text editor, else false.
7673     */
7674    public boolean onCheckIsTextEditor() {
7675        return false;
7676    }
7677
7678    /**
7679     * Create a new InputConnection for an InputMethod to interact
7680     * with the view.  The default implementation returns null, since it doesn't
7681     * support input methods.  You can override this to implement such support.
7682     * This is only needed for views that take focus and text input.
7683     *
7684     * <p>When implementing this, you probably also want to implement
7685     * {@link #onCheckIsTextEditor()} to indicate you will return a
7686     * non-null InputConnection.
7687     *
7688     * @param outAttrs Fill in with attribute information about the connection.
7689     */
7690    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7691        return null;
7692    }
7693
7694    /**
7695     * Called by the {@link android.view.inputmethod.InputMethodManager}
7696     * when a view who is not the current
7697     * input connection target is trying to make a call on the manager.  The
7698     * default implementation returns false; you can override this to return
7699     * true for certain views if you are performing InputConnection proxying
7700     * to them.
7701     * @param view The View that is making the InputMethodManager call.
7702     * @return Return true to allow the call, false to reject.
7703     */
7704    public boolean checkInputConnectionProxy(View view) {
7705        return false;
7706    }
7707
7708    /**
7709     * Show the context menu for this view. It is not safe to hold on to the
7710     * menu after returning from this method.
7711     *
7712     * You should normally not overload this method. Overload
7713     * {@link #onCreateContextMenu(ContextMenu)} or define an
7714     * {@link OnCreateContextMenuListener} to add items to the context menu.
7715     *
7716     * @param menu The context menu to populate
7717     */
7718    public void createContextMenu(ContextMenu menu) {
7719        ContextMenuInfo menuInfo = getContextMenuInfo();
7720
7721        // Sets the current menu info so all items added to menu will have
7722        // my extra info set.
7723        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7724
7725        onCreateContextMenu(menu);
7726        ListenerInfo li = mListenerInfo;
7727        if (li != null && li.mOnCreateContextMenuListener != null) {
7728            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7729        }
7730
7731        // Clear the extra information so subsequent items that aren't mine don't
7732        // have my extra info.
7733        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7734
7735        if (mParent != null) {
7736            mParent.createContextMenu(menu);
7737        }
7738    }
7739
7740    /**
7741     * Views should implement this if they have extra information to associate
7742     * with the context menu. The return result is supplied as a parameter to
7743     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7744     * callback.
7745     *
7746     * @return Extra information about the item for which the context menu
7747     *         should be shown. This information will vary across different
7748     *         subclasses of View.
7749     */
7750    protected ContextMenuInfo getContextMenuInfo() {
7751        return null;
7752    }
7753
7754    /**
7755     * Views should implement this if the view itself is going to add items to
7756     * the context menu.
7757     *
7758     * @param menu the context menu to populate
7759     */
7760    protected void onCreateContextMenu(ContextMenu menu) {
7761    }
7762
7763    /**
7764     * Implement this method to handle trackball motion events.  The
7765     * <em>relative</em> movement of the trackball since the last event
7766     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7767     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7768     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7769     * they will often be fractional values, representing the more fine-grained
7770     * movement information available from a trackball).
7771     *
7772     * @param event The motion event.
7773     * @return True if the event was handled, false otherwise.
7774     */
7775    public boolean onTrackballEvent(MotionEvent event) {
7776        return false;
7777    }
7778
7779    /**
7780     * Implement this method to handle generic motion events.
7781     * <p>
7782     * Generic motion events describe joystick movements, mouse hovers, track pad
7783     * touches, scroll wheel movements and other input events.  The
7784     * {@link MotionEvent#getSource() source} of the motion event specifies
7785     * the class of input that was received.  Implementations of this method
7786     * must examine the bits in the source before processing the event.
7787     * The following code example shows how this is done.
7788     * </p><p>
7789     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7790     * are delivered to the view under the pointer.  All other generic motion events are
7791     * delivered to the focused view.
7792     * </p>
7793     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7794     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7795     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7796     *             // process the joystick movement...
7797     *             return true;
7798     *         }
7799     *     }
7800     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7801     *         switch (event.getAction()) {
7802     *             case MotionEvent.ACTION_HOVER_MOVE:
7803     *                 // process the mouse hover movement...
7804     *                 return true;
7805     *             case MotionEvent.ACTION_SCROLL:
7806     *                 // process the scroll wheel movement...
7807     *                 return true;
7808     *         }
7809     *     }
7810     *     return super.onGenericMotionEvent(event);
7811     * }</pre>
7812     *
7813     * @param event The generic motion event being processed.
7814     * @return True if the event was handled, false otherwise.
7815     */
7816    public boolean onGenericMotionEvent(MotionEvent event) {
7817        return false;
7818    }
7819
7820    /**
7821     * Implement this method to handle hover events.
7822     * <p>
7823     * This method is called whenever a pointer is hovering into, over, or out of the
7824     * bounds of a view and the view is not currently being touched.
7825     * Hover events are represented as pointer events with action
7826     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7827     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7828     * </p>
7829     * <ul>
7830     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7831     * when the pointer enters the bounds of the view.</li>
7832     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7833     * when the pointer has already entered the bounds of the view and has moved.</li>
7834     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7835     * when the pointer has exited the bounds of the view or when the pointer is
7836     * about to go down due to a button click, tap, or similar user action that
7837     * causes the view to be touched.</li>
7838     * </ul>
7839     * <p>
7840     * The view should implement this method to return true to indicate that it is
7841     * handling the hover event, such as by changing its drawable state.
7842     * </p><p>
7843     * The default implementation calls {@link #setHovered} to update the hovered state
7844     * of the view when a hover enter or hover exit event is received, if the view
7845     * is enabled and is clickable.  The default implementation also sends hover
7846     * accessibility events.
7847     * </p>
7848     *
7849     * @param event The motion event that describes the hover.
7850     * @return True if the view handled the hover event.
7851     *
7852     * @see #isHovered
7853     * @see #setHovered
7854     * @see #onHoverChanged
7855     */
7856    public boolean onHoverEvent(MotionEvent event) {
7857        // The root view may receive hover (or touch) events that are outside the bounds of
7858        // the window.  This code ensures that we only send accessibility events for
7859        // hovers that are actually within the bounds of the root view.
7860        final int action = event.getActionMasked();
7861        if (!mSendingHoverAccessibilityEvents) {
7862            if ((action == MotionEvent.ACTION_HOVER_ENTER
7863                    || action == MotionEvent.ACTION_HOVER_MOVE)
7864                    && !hasHoveredChild()
7865                    && pointInView(event.getX(), event.getY())) {
7866                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7867                mSendingHoverAccessibilityEvents = true;
7868                requestAccessibilityFocusFromHover();
7869            }
7870        } else {
7871            if (action == MotionEvent.ACTION_HOVER_EXIT
7872                    || (action == MotionEvent.ACTION_MOVE
7873                            && !pointInView(event.getX(), event.getY()))) {
7874                mSendingHoverAccessibilityEvents = false;
7875                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7876                // If the window does not have input focus we take away accessibility
7877                // focus as soon as the user stop hovering over the view.
7878                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7879                    getViewRootImpl().setAccessibilityFocusedHost(null);
7880                }
7881            }
7882        }
7883
7884        if (isHoverable()) {
7885            switch (action) {
7886                case MotionEvent.ACTION_HOVER_ENTER:
7887                    setHovered(true);
7888                    break;
7889                case MotionEvent.ACTION_HOVER_EXIT:
7890                    setHovered(false);
7891                    break;
7892            }
7893
7894            // Dispatch the event to onGenericMotionEvent before returning true.
7895            // This is to provide compatibility with existing applications that
7896            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7897            // break because of the new default handling for hoverable views
7898            // in onHoverEvent.
7899            // Note that onGenericMotionEvent will be called by default when
7900            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7901            dispatchGenericMotionEventInternal(event);
7902            return true;
7903        }
7904
7905        return false;
7906    }
7907
7908    /**
7909     * Returns true if the view should handle {@link #onHoverEvent}
7910     * by calling {@link #setHovered} to change its hovered state.
7911     *
7912     * @return True if the view is hoverable.
7913     */
7914    private boolean isHoverable() {
7915        final int viewFlags = mViewFlags;
7916        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7917            return false;
7918        }
7919
7920        return (viewFlags & CLICKABLE) == CLICKABLE
7921                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7922    }
7923
7924    /**
7925     * Returns true if the view is currently hovered.
7926     *
7927     * @return True if the view is currently hovered.
7928     *
7929     * @see #setHovered
7930     * @see #onHoverChanged
7931     */
7932    @ViewDebug.ExportedProperty
7933    public boolean isHovered() {
7934        return (mPrivateFlags & HOVERED) != 0;
7935    }
7936
7937    /**
7938     * Sets whether the view is currently hovered.
7939     * <p>
7940     * Calling this method also changes the drawable state of the view.  This
7941     * enables the view to react to hover by using different drawable resources
7942     * to change its appearance.
7943     * </p><p>
7944     * The {@link #onHoverChanged} method is called when the hovered state changes.
7945     * </p>
7946     *
7947     * @param hovered True if the view is hovered.
7948     *
7949     * @see #isHovered
7950     * @see #onHoverChanged
7951     */
7952    public void setHovered(boolean hovered) {
7953        if (hovered) {
7954            if ((mPrivateFlags & HOVERED) == 0) {
7955                mPrivateFlags |= HOVERED;
7956                refreshDrawableState();
7957                onHoverChanged(true);
7958            }
7959        } else {
7960            if ((mPrivateFlags & HOVERED) != 0) {
7961                mPrivateFlags &= ~HOVERED;
7962                refreshDrawableState();
7963                onHoverChanged(false);
7964            }
7965        }
7966    }
7967
7968    /**
7969     * Implement this method to handle hover state changes.
7970     * <p>
7971     * This method is called whenever the hover state changes as a result of a
7972     * call to {@link #setHovered}.
7973     * </p>
7974     *
7975     * @param hovered The current hover state, as returned by {@link #isHovered}.
7976     *
7977     * @see #isHovered
7978     * @see #setHovered
7979     */
7980    public void onHoverChanged(boolean hovered) {
7981    }
7982
7983    /**
7984     * Implement this method to handle touch screen motion events.
7985     *
7986     * @param event The motion event.
7987     * @return True if the event was handled, false otherwise.
7988     */
7989    public boolean onTouchEvent(MotionEvent event) {
7990        final int viewFlags = mViewFlags;
7991
7992        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7993            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7994                setPressed(false);
7995            }
7996            // A disabled view that is clickable still consumes the touch
7997            // events, it just doesn't respond to them.
7998            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7999                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8000        }
8001
8002        if (mTouchDelegate != null) {
8003            if (mTouchDelegate.onTouchEvent(event)) {
8004                return true;
8005            }
8006        }
8007
8008        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8009                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8010            switch (event.getAction()) {
8011                case MotionEvent.ACTION_UP:
8012                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
8013                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
8014                        // take focus if we don't have it already and we should in
8015                        // touch mode.
8016                        boolean focusTaken = false;
8017                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8018                            focusTaken = requestFocus();
8019                        }
8020
8021                        if (prepressed) {
8022                            // The button is being released before we actually
8023                            // showed it as pressed.  Make it show the pressed
8024                            // state now (before scheduling the click) to ensure
8025                            // the user sees it.
8026                            setPressed(true);
8027                       }
8028
8029                        if (!mHasPerformedLongPress) {
8030                            // This is a tap, so remove the longpress check
8031                            removeLongPressCallback();
8032
8033                            // Only perform take click actions if we were in the pressed state
8034                            if (!focusTaken) {
8035                                // Use a Runnable and post this rather than calling
8036                                // performClick directly. This lets other visual state
8037                                // of the view update before click actions start.
8038                                if (mPerformClick == null) {
8039                                    mPerformClick = new PerformClick();
8040                                }
8041                                if (!post(mPerformClick)) {
8042                                    performClick();
8043                                }
8044                            }
8045                        }
8046
8047                        if (mUnsetPressedState == null) {
8048                            mUnsetPressedState = new UnsetPressedState();
8049                        }
8050
8051                        if (prepressed) {
8052                            postDelayed(mUnsetPressedState,
8053                                    ViewConfiguration.getPressedStateDuration());
8054                        } else if (!post(mUnsetPressedState)) {
8055                            // If the post failed, unpress right now
8056                            mUnsetPressedState.run();
8057                        }
8058                        removeTapCallback();
8059                    }
8060                    break;
8061
8062                case MotionEvent.ACTION_DOWN:
8063                    mHasPerformedLongPress = false;
8064
8065                    if (performButtonActionOnTouchDown(event)) {
8066                        break;
8067                    }
8068
8069                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8070                    boolean isInScrollingContainer = isInScrollingContainer();
8071
8072                    // For views inside a scrolling container, delay the pressed feedback for
8073                    // a short period in case this is a scroll.
8074                    if (isInScrollingContainer) {
8075                        mPrivateFlags |= PREPRESSED;
8076                        if (mPendingCheckForTap == null) {
8077                            mPendingCheckForTap = new CheckForTap();
8078                        }
8079                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8080                    } else {
8081                        // Not inside a scrolling container, so show the feedback right away
8082                        setPressed(true);
8083                        checkForLongClick(0);
8084                    }
8085                    break;
8086
8087                case MotionEvent.ACTION_CANCEL:
8088                    setPressed(false);
8089                    removeTapCallback();
8090                    break;
8091
8092                case MotionEvent.ACTION_MOVE:
8093                    final int x = (int) event.getX();
8094                    final int y = (int) event.getY();
8095
8096                    // Be lenient about moving outside of buttons
8097                    if (!pointInView(x, y, mTouchSlop)) {
8098                        // Outside button
8099                        removeTapCallback();
8100                        if ((mPrivateFlags & PRESSED) != 0) {
8101                            // Remove any future long press/tap checks
8102                            removeLongPressCallback();
8103
8104                            setPressed(false);
8105                        }
8106                    }
8107                    break;
8108            }
8109            return true;
8110        }
8111
8112        return false;
8113    }
8114
8115    /**
8116     * @hide
8117     */
8118    public boolean isInScrollingContainer() {
8119        ViewParent p = getParent();
8120        while (p != null && p instanceof ViewGroup) {
8121            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8122                return true;
8123            }
8124            p = p.getParent();
8125        }
8126        return false;
8127    }
8128
8129    /**
8130     * Remove the longpress detection timer.
8131     */
8132    private void removeLongPressCallback() {
8133        if (mPendingCheckForLongPress != null) {
8134          removeCallbacks(mPendingCheckForLongPress);
8135        }
8136    }
8137
8138    /**
8139     * Remove the pending click action
8140     */
8141    private void removePerformClickCallback() {
8142        if (mPerformClick != null) {
8143            removeCallbacks(mPerformClick);
8144        }
8145    }
8146
8147    /**
8148     * Remove the prepress detection timer.
8149     */
8150    private void removeUnsetPressCallback() {
8151        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
8152            setPressed(false);
8153            removeCallbacks(mUnsetPressedState);
8154        }
8155    }
8156
8157    /**
8158     * Remove the tap detection timer.
8159     */
8160    private void removeTapCallback() {
8161        if (mPendingCheckForTap != null) {
8162            mPrivateFlags &= ~PREPRESSED;
8163            removeCallbacks(mPendingCheckForTap);
8164        }
8165    }
8166
8167    /**
8168     * Cancels a pending long press.  Your subclass can use this if you
8169     * want the context menu to come up if the user presses and holds
8170     * at the same place, but you don't want it to come up if they press
8171     * and then move around enough to cause scrolling.
8172     */
8173    public void cancelLongPress() {
8174        removeLongPressCallback();
8175
8176        /*
8177         * The prepressed state handled by the tap callback is a display
8178         * construct, but the tap callback will post a long press callback
8179         * less its own timeout. Remove it here.
8180         */
8181        removeTapCallback();
8182    }
8183
8184    /**
8185     * Remove the pending callback for sending a
8186     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8187     */
8188    private void removeSendViewScrolledAccessibilityEventCallback() {
8189        if (mSendViewScrolledAccessibilityEvent != null) {
8190            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8191            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8192        }
8193    }
8194
8195    /**
8196     * Sets the TouchDelegate for this View.
8197     */
8198    public void setTouchDelegate(TouchDelegate delegate) {
8199        mTouchDelegate = delegate;
8200    }
8201
8202    /**
8203     * Gets the TouchDelegate for this View.
8204     */
8205    public TouchDelegate getTouchDelegate() {
8206        return mTouchDelegate;
8207    }
8208
8209    /**
8210     * Set flags controlling behavior of this view.
8211     *
8212     * @param flags Constant indicating the value which should be set
8213     * @param mask Constant indicating the bit range that should be changed
8214     */
8215    void setFlags(int flags, int mask) {
8216        int old = mViewFlags;
8217        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8218
8219        int changed = mViewFlags ^ old;
8220        if (changed == 0) {
8221            return;
8222        }
8223        int privateFlags = mPrivateFlags;
8224
8225        /* Check if the FOCUSABLE bit has changed */
8226        if (((changed & FOCUSABLE_MASK) != 0) &&
8227                ((privateFlags & HAS_BOUNDS) !=0)) {
8228            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8229                    && ((privateFlags & FOCUSED) != 0)) {
8230                /* Give up focus if we are no longer focusable */
8231                clearFocus();
8232            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8233                    && ((privateFlags & FOCUSED) == 0)) {
8234                /*
8235                 * Tell the view system that we are now available to take focus
8236                 * if no one else already has it.
8237                 */
8238                if (mParent != null) mParent.focusableViewAvailable(this);
8239            }
8240            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8241                notifyAccessibilityStateChanged();
8242            }
8243        }
8244
8245        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8246            if ((changed & VISIBILITY_MASK) != 0) {
8247                /*
8248                 * If this view is becoming visible, invalidate it in case it changed while
8249                 * it was not visible. Marking it drawn ensures that the invalidation will
8250                 * go through.
8251                 */
8252                mPrivateFlags |= DRAWN;
8253                invalidate(true);
8254
8255                needGlobalAttributesUpdate(true);
8256
8257                // a view becoming visible is worth notifying the parent
8258                // about in case nothing has focus.  even if this specific view
8259                // isn't focusable, it may contain something that is, so let
8260                // the root view try to give this focus if nothing else does.
8261                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8262                    mParent.focusableViewAvailable(this);
8263                }
8264            }
8265        }
8266
8267        /* Check if the GONE bit has changed */
8268        if ((changed & GONE) != 0) {
8269            needGlobalAttributesUpdate(false);
8270            requestLayout();
8271
8272            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8273                if (hasFocus()) clearFocus();
8274                clearAccessibilityFocus();
8275                destroyDrawingCache();
8276                if (mParent instanceof View) {
8277                    // GONE views noop invalidation, so invalidate the parent
8278                    ((View) mParent).invalidate(true);
8279                }
8280                // Mark the view drawn to ensure that it gets invalidated properly the next
8281                // time it is visible and gets invalidated
8282                mPrivateFlags |= DRAWN;
8283            }
8284            if (mAttachInfo != null) {
8285                mAttachInfo.mViewVisibilityChanged = true;
8286            }
8287        }
8288
8289        /* Check if the VISIBLE bit has changed */
8290        if ((changed & INVISIBLE) != 0) {
8291            needGlobalAttributesUpdate(false);
8292            /*
8293             * If this view is becoming invisible, set the DRAWN flag so that
8294             * the next invalidate() will not be skipped.
8295             */
8296            mPrivateFlags |= DRAWN;
8297
8298            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8299                // root view becoming invisible shouldn't clear focus and accessibility focus
8300                if (getRootView() != this) {
8301                    clearFocus();
8302                    clearAccessibilityFocus();
8303                }
8304            }
8305            if (mAttachInfo != null) {
8306                mAttachInfo.mViewVisibilityChanged = true;
8307            }
8308        }
8309
8310        if ((changed & VISIBILITY_MASK) != 0) {
8311            if (mParent instanceof ViewGroup) {
8312                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8313                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8314                ((View) mParent).invalidate(true);
8315            } else if (mParent != null) {
8316                mParent.invalidateChild(this, null);
8317            }
8318            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8319        }
8320
8321        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8322            destroyDrawingCache();
8323        }
8324
8325        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8326            destroyDrawingCache();
8327            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8328            invalidateParentCaches();
8329        }
8330
8331        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8332            destroyDrawingCache();
8333            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8334        }
8335
8336        if ((changed & DRAW_MASK) != 0) {
8337            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8338                if (mBackground != null) {
8339                    mPrivateFlags &= ~SKIP_DRAW;
8340                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8341                } else {
8342                    mPrivateFlags |= SKIP_DRAW;
8343                }
8344            } else {
8345                mPrivateFlags &= ~SKIP_DRAW;
8346            }
8347            requestLayout();
8348            invalidate(true);
8349        }
8350
8351        if ((changed & KEEP_SCREEN_ON) != 0) {
8352            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8353                mParent.recomputeViewAttributes(this);
8354            }
8355        }
8356
8357        if (AccessibilityManager.getInstance(mContext).isEnabled()
8358                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8359                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8360            notifyAccessibilityStateChanged();
8361        }
8362    }
8363
8364    /**
8365     * Change the view's z order in the tree, so it's on top of other sibling
8366     * views
8367     */
8368    public void bringToFront() {
8369        if (mParent != null) {
8370            mParent.bringChildToFront(this);
8371        }
8372    }
8373
8374    /**
8375     * This is called in response to an internal scroll in this view (i.e., the
8376     * view scrolled its own contents). This is typically as a result of
8377     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8378     * called.
8379     *
8380     * @param l Current horizontal scroll origin.
8381     * @param t Current vertical scroll origin.
8382     * @param oldl Previous horizontal scroll origin.
8383     * @param oldt Previous vertical scroll origin.
8384     */
8385    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8386        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8387            postSendViewScrolledAccessibilityEventCallback();
8388        }
8389
8390        mBackgroundSizeChanged = true;
8391
8392        final AttachInfo ai = mAttachInfo;
8393        if (ai != null) {
8394            ai.mViewScrollChanged = true;
8395        }
8396    }
8397
8398    /**
8399     * Interface definition for a callback to be invoked when the layout bounds of a view
8400     * changes due to layout processing.
8401     */
8402    public interface OnLayoutChangeListener {
8403        /**
8404         * Called when the focus state of a view has changed.
8405         *
8406         * @param v The view whose state has changed.
8407         * @param left The new value of the view's left property.
8408         * @param top The new value of the view's top property.
8409         * @param right The new value of the view's right property.
8410         * @param bottom The new value of the view's bottom property.
8411         * @param oldLeft The previous value of the view's left property.
8412         * @param oldTop The previous value of the view's top property.
8413         * @param oldRight The previous value of the view's right property.
8414         * @param oldBottom The previous value of the view's bottom property.
8415         */
8416        void onLayoutChange(View v, int left, int top, int right, int bottom,
8417            int oldLeft, int oldTop, int oldRight, int oldBottom);
8418    }
8419
8420    /**
8421     * This is called during layout when the size of this view has changed. If
8422     * you were just added to the view hierarchy, you're called with the old
8423     * values of 0.
8424     *
8425     * @param w Current width of this view.
8426     * @param h Current height of this view.
8427     * @param oldw Old width of this view.
8428     * @param oldh Old height of this view.
8429     */
8430    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8431    }
8432
8433    /**
8434     * Called by draw to draw the child views. This may be overridden
8435     * by derived classes to gain control just before its children are drawn
8436     * (but after its own view has been drawn).
8437     * @param canvas the canvas on which to draw the view
8438     */
8439    protected void dispatchDraw(Canvas canvas) {
8440
8441    }
8442
8443    /**
8444     * Gets the parent of this view. Note that the parent is a
8445     * ViewParent and not necessarily a View.
8446     *
8447     * @return Parent of this view.
8448     */
8449    public final ViewParent getParent() {
8450        return mParent;
8451    }
8452
8453    /**
8454     * Set the horizontal scrolled position of your view. This will cause a call to
8455     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8456     * invalidated.
8457     * @param value the x position to scroll to
8458     */
8459    public void setScrollX(int value) {
8460        scrollTo(value, mScrollY);
8461    }
8462
8463    /**
8464     * Set the vertical scrolled position of your view. This will cause a call to
8465     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8466     * invalidated.
8467     * @param value the y position to scroll to
8468     */
8469    public void setScrollY(int value) {
8470        scrollTo(mScrollX, value);
8471    }
8472
8473    /**
8474     * Return the scrolled left position of this view. This is the left edge of
8475     * the displayed part of your view. You do not need to draw any pixels
8476     * farther left, since those are outside of the frame of your view on
8477     * screen.
8478     *
8479     * @return The left edge of the displayed part of your view, in pixels.
8480     */
8481    public final int getScrollX() {
8482        return mScrollX;
8483    }
8484
8485    /**
8486     * Return the scrolled top position of this view. This is the top edge of
8487     * the displayed part of your view. You do not need to draw any pixels above
8488     * it, since those are outside of the frame of your view on screen.
8489     *
8490     * @return The top edge of the displayed part of your view, in pixels.
8491     */
8492    public final int getScrollY() {
8493        return mScrollY;
8494    }
8495
8496    /**
8497     * Return the width of the your view.
8498     *
8499     * @return The width of your view, in pixels.
8500     */
8501    @ViewDebug.ExportedProperty(category = "layout")
8502    public final int getWidth() {
8503        return mRight - mLeft;
8504    }
8505
8506    /**
8507     * Return the height of your view.
8508     *
8509     * @return The height of your view, in pixels.
8510     */
8511    @ViewDebug.ExportedProperty(category = "layout")
8512    public final int getHeight() {
8513        return mBottom - mTop;
8514    }
8515
8516    /**
8517     * Return the visible drawing bounds of your view. Fills in the output
8518     * rectangle with the values from getScrollX(), getScrollY(),
8519     * getWidth(), and getHeight().
8520     *
8521     * @param outRect The (scrolled) drawing bounds of the view.
8522     */
8523    public void getDrawingRect(Rect outRect) {
8524        outRect.left = mScrollX;
8525        outRect.top = mScrollY;
8526        outRect.right = mScrollX + (mRight - mLeft);
8527        outRect.bottom = mScrollY + (mBottom - mTop);
8528    }
8529
8530    /**
8531     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8532     * raw width component (that is the result is masked by
8533     * {@link #MEASURED_SIZE_MASK}).
8534     *
8535     * @return The raw measured width of this view.
8536     */
8537    public final int getMeasuredWidth() {
8538        return mMeasuredWidth & MEASURED_SIZE_MASK;
8539    }
8540
8541    /**
8542     * Return the full width measurement information for this view as computed
8543     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8544     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8545     * This should be used during measurement and layout calculations only. Use
8546     * {@link #getWidth()} to see how wide a view is after layout.
8547     *
8548     * @return The measured width of this view as a bit mask.
8549     */
8550    public final int getMeasuredWidthAndState() {
8551        return mMeasuredWidth;
8552    }
8553
8554    /**
8555     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8556     * raw width component (that is the result is masked by
8557     * {@link #MEASURED_SIZE_MASK}).
8558     *
8559     * @return The raw measured height of this view.
8560     */
8561    public final int getMeasuredHeight() {
8562        return mMeasuredHeight & MEASURED_SIZE_MASK;
8563    }
8564
8565    /**
8566     * Return the full height measurement information for this view as computed
8567     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8568     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8569     * This should be used during measurement and layout calculations only. Use
8570     * {@link #getHeight()} to see how wide a view is after layout.
8571     *
8572     * @return The measured width of this view as a bit mask.
8573     */
8574    public final int getMeasuredHeightAndState() {
8575        return mMeasuredHeight;
8576    }
8577
8578    /**
8579     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8580     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8581     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8582     * and the height component is at the shifted bits
8583     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8584     */
8585    public final int getMeasuredState() {
8586        return (mMeasuredWidth&MEASURED_STATE_MASK)
8587                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8588                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8589    }
8590
8591    /**
8592     * The transform matrix of this view, which is calculated based on the current
8593     * roation, scale, and pivot properties.
8594     *
8595     * @see #getRotation()
8596     * @see #getScaleX()
8597     * @see #getScaleY()
8598     * @see #getPivotX()
8599     * @see #getPivotY()
8600     * @return The current transform matrix for the view
8601     */
8602    public Matrix getMatrix() {
8603        if (mTransformationInfo != null) {
8604            updateMatrix();
8605            return mTransformationInfo.mMatrix;
8606        }
8607        return Matrix.IDENTITY_MATRIX;
8608    }
8609
8610    /**
8611     * Utility function to determine if the value is far enough away from zero to be
8612     * considered non-zero.
8613     * @param value A floating point value to check for zero-ness
8614     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8615     */
8616    private static boolean nonzero(float value) {
8617        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8618    }
8619
8620    /**
8621     * Returns true if the transform matrix is the identity matrix.
8622     * Recomputes the matrix if necessary.
8623     *
8624     * @return True if the transform matrix is the identity matrix, false otherwise.
8625     */
8626    final boolean hasIdentityMatrix() {
8627        if (mTransformationInfo != null) {
8628            updateMatrix();
8629            return mTransformationInfo.mMatrixIsIdentity;
8630        }
8631        return true;
8632    }
8633
8634    void ensureTransformationInfo() {
8635        if (mTransformationInfo == null) {
8636            mTransformationInfo = new TransformationInfo();
8637        }
8638    }
8639
8640    /**
8641     * Recomputes the transform matrix if necessary.
8642     */
8643    private void updateMatrix() {
8644        final TransformationInfo info = mTransformationInfo;
8645        if (info == null) {
8646            return;
8647        }
8648        if (info.mMatrixDirty) {
8649            // transform-related properties have changed since the last time someone
8650            // asked for the matrix; recalculate it with the current values
8651
8652            // Figure out if we need to update the pivot point
8653            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8654                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8655                    info.mPrevWidth = mRight - mLeft;
8656                    info.mPrevHeight = mBottom - mTop;
8657                    info.mPivotX = info.mPrevWidth / 2f;
8658                    info.mPivotY = info.mPrevHeight / 2f;
8659                }
8660            }
8661            info.mMatrix.reset();
8662            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8663                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8664                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8665                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8666            } else {
8667                if (info.mCamera == null) {
8668                    info.mCamera = new Camera();
8669                    info.matrix3D = new Matrix();
8670                }
8671                info.mCamera.save();
8672                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8673                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8674                info.mCamera.getMatrix(info.matrix3D);
8675                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8676                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8677                        info.mPivotY + info.mTranslationY);
8678                info.mMatrix.postConcat(info.matrix3D);
8679                info.mCamera.restore();
8680            }
8681            info.mMatrixDirty = false;
8682            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8683            info.mInverseMatrixDirty = true;
8684        }
8685    }
8686
8687    /**
8688     * Utility method to retrieve the inverse of the current mMatrix property.
8689     * We cache the matrix to avoid recalculating it when transform properties
8690     * have not changed.
8691     *
8692     * @return The inverse of the current matrix of this view.
8693     */
8694    final Matrix getInverseMatrix() {
8695        final TransformationInfo info = mTransformationInfo;
8696        if (info != null) {
8697            updateMatrix();
8698            if (info.mInverseMatrixDirty) {
8699                if (info.mInverseMatrix == null) {
8700                    info.mInverseMatrix = new Matrix();
8701                }
8702                info.mMatrix.invert(info.mInverseMatrix);
8703                info.mInverseMatrixDirty = false;
8704            }
8705            return info.mInverseMatrix;
8706        }
8707        return Matrix.IDENTITY_MATRIX;
8708    }
8709
8710    /**
8711     * Gets the distance along the Z axis from the camera to this view.
8712     *
8713     * @see #setCameraDistance(float)
8714     *
8715     * @return The distance along the Z axis.
8716     */
8717    public float getCameraDistance() {
8718        ensureTransformationInfo();
8719        final float dpi = mResources.getDisplayMetrics().densityDpi;
8720        final TransformationInfo info = mTransformationInfo;
8721        if (info.mCamera == null) {
8722            info.mCamera = new Camera();
8723            info.matrix3D = new Matrix();
8724        }
8725        return -(info.mCamera.getLocationZ() * dpi);
8726    }
8727
8728    /**
8729     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8730     * views are drawn) from the camera to this view. The camera's distance
8731     * affects 3D transformations, for instance rotations around the X and Y
8732     * axis. If the rotationX or rotationY properties are changed and this view is
8733     * large (more than half the size of the screen), it is recommended to always
8734     * use a camera distance that's greater than the height (X axis rotation) or
8735     * the width (Y axis rotation) of this view.</p>
8736     *
8737     * <p>The distance of the camera from the view plane can have an affect on the
8738     * perspective distortion of the view when it is rotated around the x or y axis.
8739     * For example, a large distance will result in a large viewing angle, and there
8740     * will not be much perspective distortion of the view as it rotates. A short
8741     * distance may cause much more perspective distortion upon rotation, and can
8742     * also result in some drawing artifacts if the rotated view ends up partially
8743     * behind the camera (which is why the recommendation is to use a distance at
8744     * least as far as the size of the view, if the view is to be rotated.)</p>
8745     *
8746     * <p>The distance is expressed in "depth pixels." The default distance depends
8747     * on the screen density. For instance, on a medium density display, the
8748     * default distance is 1280. On a high density display, the default distance
8749     * is 1920.</p>
8750     *
8751     * <p>If you want to specify a distance that leads to visually consistent
8752     * results across various densities, use the following formula:</p>
8753     * <pre>
8754     * float scale = context.getResources().getDisplayMetrics().density;
8755     * view.setCameraDistance(distance * scale);
8756     * </pre>
8757     *
8758     * <p>The density scale factor of a high density display is 1.5,
8759     * and 1920 = 1280 * 1.5.</p>
8760     *
8761     * @param distance The distance in "depth pixels", if negative the opposite
8762     *        value is used
8763     *
8764     * @see #setRotationX(float)
8765     * @see #setRotationY(float)
8766     */
8767    public void setCameraDistance(float distance) {
8768        invalidateViewProperty(true, false);
8769
8770        ensureTransformationInfo();
8771        final float dpi = mResources.getDisplayMetrics().densityDpi;
8772        final TransformationInfo info = mTransformationInfo;
8773        if (info.mCamera == null) {
8774            info.mCamera = new Camera();
8775            info.matrix3D = new Matrix();
8776        }
8777
8778        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8779        info.mMatrixDirty = true;
8780
8781        invalidateViewProperty(false, false);
8782        if (mDisplayList != null) {
8783            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8784        }
8785        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8786            // View was rejected last time it was drawn by its parent; this may have changed
8787            invalidateParentIfNeeded();
8788        }
8789    }
8790
8791    /**
8792     * The degrees that the view is rotated around the pivot point.
8793     *
8794     * @see #setRotation(float)
8795     * @see #getPivotX()
8796     * @see #getPivotY()
8797     *
8798     * @return The degrees of rotation.
8799     */
8800    @ViewDebug.ExportedProperty(category = "drawing")
8801    public float getRotation() {
8802        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8803    }
8804
8805    /**
8806     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8807     * result in clockwise rotation.
8808     *
8809     * @param rotation The degrees of rotation.
8810     *
8811     * @see #getRotation()
8812     * @see #getPivotX()
8813     * @see #getPivotY()
8814     * @see #setRotationX(float)
8815     * @see #setRotationY(float)
8816     *
8817     * @attr ref android.R.styleable#View_rotation
8818     */
8819    public void setRotation(float rotation) {
8820        ensureTransformationInfo();
8821        final TransformationInfo info = mTransformationInfo;
8822        if (info.mRotation != rotation) {
8823            // Double-invalidation is necessary to capture view's old and new areas
8824            invalidateViewProperty(true, false);
8825            info.mRotation = rotation;
8826            info.mMatrixDirty = true;
8827            invalidateViewProperty(false, true);
8828            if (mDisplayList != null) {
8829                mDisplayList.setRotation(rotation);
8830            }
8831            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8832                // View was rejected last time it was drawn by its parent; this may have changed
8833                invalidateParentIfNeeded();
8834            }
8835        }
8836    }
8837
8838    /**
8839     * The degrees that the view is rotated around the vertical axis through the pivot point.
8840     *
8841     * @see #getPivotX()
8842     * @see #getPivotY()
8843     * @see #setRotationY(float)
8844     *
8845     * @return The degrees of Y rotation.
8846     */
8847    @ViewDebug.ExportedProperty(category = "drawing")
8848    public float getRotationY() {
8849        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8850    }
8851
8852    /**
8853     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8854     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8855     * down the y axis.
8856     *
8857     * When rotating large views, it is recommended to adjust the camera distance
8858     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8859     *
8860     * @param rotationY The degrees of Y rotation.
8861     *
8862     * @see #getRotationY()
8863     * @see #getPivotX()
8864     * @see #getPivotY()
8865     * @see #setRotation(float)
8866     * @see #setRotationX(float)
8867     * @see #setCameraDistance(float)
8868     *
8869     * @attr ref android.R.styleable#View_rotationY
8870     */
8871    public void setRotationY(float rotationY) {
8872        ensureTransformationInfo();
8873        final TransformationInfo info = mTransformationInfo;
8874        if (info.mRotationY != rotationY) {
8875            invalidateViewProperty(true, false);
8876            info.mRotationY = rotationY;
8877            info.mMatrixDirty = true;
8878            invalidateViewProperty(false, true);
8879            if (mDisplayList != null) {
8880                mDisplayList.setRotationY(rotationY);
8881            }
8882            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8883                // View was rejected last time it was drawn by its parent; this may have changed
8884                invalidateParentIfNeeded();
8885            }
8886        }
8887    }
8888
8889    /**
8890     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8891     *
8892     * @see #getPivotX()
8893     * @see #getPivotY()
8894     * @see #setRotationX(float)
8895     *
8896     * @return The degrees of X rotation.
8897     */
8898    @ViewDebug.ExportedProperty(category = "drawing")
8899    public float getRotationX() {
8900        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8901    }
8902
8903    /**
8904     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8905     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8906     * x axis.
8907     *
8908     * When rotating large views, it is recommended to adjust the camera distance
8909     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8910     *
8911     * @param rotationX The degrees of X rotation.
8912     *
8913     * @see #getRotationX()
8914     * @see #getPivotX()
8915     * @see #getPivotY()
8916     * @see #setRotation(float)
8917     * @see #setRotationY(float)
8918     * @see #setCameraDistance(float)
8919     *
8920     * @attr ref android.R.styleable#View_rotationX
8921     */
8922    public void setRotationX(float rotationX) {
8923        ensureTransformationInfo();
8924        final TransformationInfo info = mTransformationInfo;
8925        if (info.mRotationX != rotationX) {
8926            invalidateViewProperty(true, false);
8927            info.mRotationX = rotationX;
8928            info.mMatrixDirty = true;
8929            invalidateViewProperty(false, true);
8930            if (mDisplayList != null) {
8931                mDisplayList.setRotationX(rotationX);
8932            }
8933            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8934                // View was rejected last time it was drawn by its parent; this may have changed
8935                invalidateParentIfNeeded();
8936            }
8937        }
8938    }
8939
8940    /**
8941     * The amount that the view is scaled in x around the pivot point, as a proportion of
8942     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8943     *
8944     * <p>By default, this is 1.0f.
8945     *
8946     * @see #getPivotX()
8947     * @see #getPivotY()
8948     * @return The scaling factor.
8949     */
8950    @ViewDebug.ExportedProperty(category = "drawing")
8951    public float getScaleX() {
8952        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8953    }
8954
8955    /**
8956     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8957     * the view's unscaled width. A value of 1 means that no scaling is applied.
8958     *
8959     * @param scaleX The scaling factor.
8960     * @see #getPivotX()
8961     * @see #getPivotY()
8962     *
8963     * @attr ref android.R.styleable#View_scaleX
8964     */
8965    public void setScaleX(float scaleX) {
8966        ensureTransformationInfo();
8967        final TransformationInfo info = mTransformationInfo;
8968        if (info.mScaleX != scaleX) {
8969            invalidateViewProperty(true, false);
8970            info.mScaleX = scaleX;
8971            info.mMatrixDirty = true;
8972            invalidateViewProperty(false, true);
8973            if (mDisplayList != null) {
8974                mDisplayList.setScaleX(scaleX);
8975            }
8976            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8977                // View was rejected last time it was drawn by its parent; this may have changed
8978                invalidateParentIfNeeded();
8979            }
8980        }
8981    }
8982
8983    /**
8984     * The amount that the view is scaled in y around the pivot point, as a proportion of
8985     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8986     *
8987     * <p>By default, this is 1.0f.
8988     *
8989     * @see #getPivotX()
8990     * @see #getPivotY()
8991     * @return The scaling factor.
8992     */
8993    @ViewDebug.ExportedProperty(category = "drawing")
8994    public float getScaleY() {
8995        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8996    }
8997
8998    /**
8999     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9000     * the view's unscaled width. A value of 1 means that no scaling is applied.
9001     *
9002     * @param scaleY The scaling factor.
9003     * @see #getPivotX()
9004     * @see #getPivotY()
9005     *
9006     * @attr ref android.R.styleable#View_scaleY
9007     */
9008    public void setScaleY(float scaleY) {
9009        ensureTransformationInfo();
9010        final TransformationInfo info = mTransformationInfo;
9011        if (info.mScaleY != scaleY) {
9012            invalidateViewProperty(true, false);
9013            info.mScaleY = scaleY;
9014            info.mMatrixDirty = true;
9015            invalidateViewProperty(false, true);
9016            if (mDisplayList != null) {
9017                mDisplayList.setScaleY(scaleY);
9018            }
9019            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9020                // View was rejected last time it was drawn by its parent; this may have changed
9021                invalidateParentIfNeeded();
9022            }
9023        }
9024    }
9025
9026    /**
9027     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9028     * and {@link #setScaleX(float) scaled}.
9029     *
9030     * @see #getRotation()
9031     * @see #getScaleX()
9032     * @see #getScaleY()
9033     * @see #getPivotY()
9034     * @return The x location of the pivot point.
9035     *
9036     * @attr ref android.R.styleable#View_transformPivotX
9037     */
9038    @ViewDebug.ExportedProperty(category = "drawing")
9039    public float getPivotX() {
9040        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9041    }
9042
9043    /**
9044     * Sets the x location of the point around which the view is
9045     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9046     * By default, the pivot point is centered on the object.
9047     * Setting this property disables this behavior and causes the view to use only the
9048     * explicitly set pivotX and pivotY values.
9049     *
9050     * @param pivotX The x location of the pivot point.
9051     * @see #getRotation()
9052     * @see #getScaleX()
9053     * @see #getScaleY()
9054     * @see #getPivotY()
9055     *
9056     * @attr ref android.R.styleable#View_transformPivotX
9057     */
9058    public void setPivotX(float pivotX) {
9059        ensureTransformationInfo();
9060        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
9061        final TransformationInfo info = mTransformationInfo;
9062        if (info.mPivotX != pivotX) {
9063            invalidateViewProperty(true, false);
9064            info.mPivotX = pivotX;
9065            info.mMatrixDirty = true;
9066            invalidateViewProperty(false, true);
9067            if (mDisplayList != null) {
9068                mDisplayList.setPivotX(pivotX);
9069            }
9070            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9071                // View was rejected last time it was drawn by its parent; this may have changed
9072                invalidateParentIfNeeded();
9073            }
9074        }
9075    }
9076
9077    /**
9078     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9079     * and {@link #setScaleY(float) scaled}.
9080     *
9081     * @see #getRotation()
9082     * @see #getScaleX()
9083     * @see #getScaleY()
9084     * @see #getPivotY()
9085     * @return The y location of the pivot point.
9086     *
9087     * @attr ref android.R.styleable#View_transformPivotY
9088     */
9089    @ViewDebug.ExportedProperty(category = "drawing")
9090    public float getPivotY() {
9091        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9092    }
9093
9094    /**
9095     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9096     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9097     * Setting this property disables this behavior and causes the view to use only the
9098     * explicitly set pivotX and pivotY values.
9099     *
9100     * @param pivotY The y location of the pivot point.
9101     * @see #getRotation()
9102     * @see #getScaleX()
9103     * @see #getScaleY()
9104     * @see #getPivotY()
9105     *
9106     * @attr ref android.R.styleable#View_transformPivotY
9107     */
9108    public void setPivotY(float pivotY) {
9109        ensureTransformationInfo();
9110        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
9111        final TransformationInfo info = mTransformationInfo;
9112        if (info.mPivotY != pivotY) {
9113            invalidateViewProperty(true, false);
9114            info.mPivotY = pivotY;
9115            info.mMatrixDirty = true;
9116            invalidateViewProperty(false, true);
9117            if (mDisplayList != null) {
9118                mDisplayList.setPivotY(pivotY);
9119            }
9120            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9121                // View was rejected last time it was drawn by its parent; this may have changed
9122                invalidateParentIfNeeded();
9123            }
9124        }
9125    }
9126
9127    /**
9128     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9129     * completely transparent and 1 means the view is completely opaque.
9130     *
9131     * <p>By default this is 1.0f.
9132     * @return The opacity of the view.
9133     */
9134    @ViewDebug.ExportedProperty(category = "drawing")
9135    public float getAlpha() {
9136        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9137    }
9138
9139    /**
9140     * Returns whether this View has content which overlaps. This function, intended to be
9141     * overridden by specific View types, is an optimization when alpha is set on a view. If
9142     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9143     * and then composited it into place, which can be expensive. If the view has no overlapping
9144     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9145     * An example of overlapping rendering is a TextView with a background image, such as a
9146     * Button. An example of non-overlapping rendering is a TextView with no background, or
9147     * an ImageView with only the foreground image. The default implementation returns true;
9148     * subclasses should override if they have cases which can be optimized.
9149     *
9150     * @return true if the content in this view might overlap, false otherwise.
9151     */
9152    public boolean hasOverlappingRendering() {
9153        return true;
9154    }
9155
9156    /**
9157     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9158     * completely transparent and 1 means the view is completely opaque.</p>
9159     *
9160     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9161     * responsible for applying the opacity itself. Otherwise, calling this method is
9162     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
9163     * setting a hardware layer.</p>
9164     *
9165     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
9166     * performance implications. It is generally best to use the alpha property sparingly and
9167     * transiently, as in the case of fading animations.</p>
9168     *
9169     * @param alpha The opacity of the view.
9170     *
9171     * @see #setLayerType(int, android.graphics.Paint)
9172     *
9173     * @attr ref android.R.styleable#View_alpha
9174     */
9175    public void setAlpha(float alpha) {
9176        ensureTransformationInfo();
9177        if (mTransformationInfo.mAlpha != alpha) {
9178            mTransformationInfo.mAlpha = alpha;
9179            if (onSetAlpha((int) (alpha * 255))) {
9180                mPrivateFlags |= ALPHA_SET;
9181                // subclass is handling alpha - don't optimize rendering cache invalidation
9182                invalidateParentCaches();
9183                invalidate(true);
9184            } else {
9185                mPrivateFlags &= ~ALPHA_SET;
9186                invalidateViewProperty(true, false);
9187                if (mDisplayList != null) {
9188                    mDisplayList.setAlpha(alpha);
9189                }
9190            }
9191        }
9192    }
9193
9194    /**
9195     * Faster version of setAlpha() which performs the same steps except there are
9196     * no calls to invalidate(). The caller of this function should perform proper invalidation
9197     * on the parent and this object. The return value indicates whether the subclass handles
9198     * alpha (the return value for onSetAlpha()).
9199     *
9200     * @param alpha The new value for the alpha property
9201     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9202     *         the new value for the alpha property is different from the old value
9203     */
9204    boolean setAlphaNoInvalidation(float alpha) {
9205        ensureTransformationInfo();
9206        if (mTransformationInfo.mAlpha != alpha) {
9207            mTransformationInfo.mAlpha = alpha;
9208            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9209            if (subclassHandlesAlpha) {
9210                mPrivateFlags |= ALPHA_SET;
9211                return true;
9212            } else {
9213                mPrivateFlags &= ~ALPHA_SET;
9214                if (mDisplayList != null) {
9215                    mDisplayList.setAlpha(alpha);
9216                }
9217            }
9218        }
9219        return false;
9220    }
9221
9222    /**
9223     * Top position of this view relative to its parent.
9224     *
9225     * @return The top of this view, in pixels.
9226     */
9227    @ViewDebug.CapturedViewProperty
9228    public final int getTop() {
9229        return mTop;
9230    }
9231
9232    /**
9233     * Sets the top position of this view relative to its parent. This method is meant to be called
9234     * by the layout system and should not generally be called otherwise, because the property
9235     * may be changed at any time by the layout.
9236     *
9237     * @param top The top of this view, in pixels.
9238     */
9239    public final void setTop(int top) {
9240        if (top != mTop) {
9241            updateMatrix();
9242            final boolean matrixIsIdentity = mTransformationInfo == null
9243                    || mTransformationInfo.mMatrixIsIdentity;
9244            if (matrixIsIdentity) {
9245                if (mAttachInfo != null) {
9246                    int minTop;
9247                    int yLoc;
9248                    if (top < mTop) {
9249                        minTop = top;
9250                        yLoc = top - mTop;
9251                    } else {
9252                        minTop = mTop;
9253                        yLoc = 0;
9254                    }
9255                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9256                }
9257            } else {
9258                // Double-invalidation is necessary to capture view's old and new areas
9259                invalidate(true);
9260            }
9261
9262            int width = mRight - mLeft;
9263            int oldHeight = mBottom - mTop;
9264
9265            mTop = top;
9266            if (mDisplayList != null) {
9267                mDisplayList.setTop(mTop);
9268            }
9269
9270            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9271
9272            if (!matrixIsIdentity) {
9273                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9274                    // A change in dimension means an auto-centered pivot point changes, too
9275                    mTransformationInfo.mMatrixDirty = true;
9276                }
9277                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9278                invalidate(true);
9279            }
9280            mBackgroundSizeChanged = true;
9281            invalidateParentIfNeeded();
9282            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9283                // View was rejected last time it was drawn by its parent; this may have changed
9284                invalidateParentIfNeeded();
9285            }
9286        }
9287    }
9288
9289    /**
9290     * Bottom position of this view relative to its parent.
9291     *
9292     * @return The bottom of this view, in pixels.
9293     */
9294    @ViewDebug.CapturedViewProperty
9295    public final int getBottom() {
9296        return mBottom;
9297    }
9298
9299    /**
9300     * True if this view has changed since the last time being drawn.
9301     *
9302     * @return The dirty state of this view.
9303     */
9304    public boolean isDirty() {
9305        return (mPrivateFlags & DIRTY_MASK) != 0;
9306    }
9307
9308    /**
9309     * Sets the bottom position of this view relative to its parent. This method is meant to be
9310     * called by the layout system and should not generally be called otherwise, because the
9311     * property may be changed at any time by the layout.
9312     *
9313     * @param bottom The bottom of this view, in pixels.
9314     */
9315    public final void setBottom(int bottom) {
9316        if (bottom != mBottom) {
9317            updateMatrix();
9318            final boolean matrixIsIdentity = mTransformationInfo == null
9319                    || mTransformationInfo.mMatrixIsIdentity;
9320            if (matrixIsIdentity) {
9321                if (mAttachInfo != null) {
9322                    int maxBottom;
9323                    if (bottom < mBottom) {
9324                        maxBottom = mBottom;
9325                    } else {
9326                        maxBottom = bottom;
9327                    }
9328                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9329                }
9330            } else {
9331                // Double-invalidation is necessary to capture view's old and new areas
9332                invalidate(true);
9333            }
9334
9335            int width = mRight - mLeft;
9336            int oldHeight = mBottom - mTop;
9337
9338            mBottom = bottom;
9339            if (mDisplayList != null) {
9340                mDisplayList.setBottom(mBottom);
9341            }
9342
9343            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9344
9345            if (!matrixIsIdentity) {
9346                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9347                    // A change in dimension means an auto-centered pivot point changes, too
9348                    mTransformationInfo.mMatrixDirty = true;
9349                }
9350                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9351                invalidate(true);
9352            }
9353            mBackgroundSizeChanged = true;
9354            invalidateParentIfNeeded();
9355            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9356                // View was rejected last time it was drawn by its parent; this may have changed
9357                invalidateParentIfNeeded();
9358            }
9359        }
9360    }
9361
9362    /**
9363     * Left position of this view relative to its parent.
9364     *
9365     * @return The left edge of this view, in pixels.
9366     */
9367    @ViewDebug.CapturedViewProperty
9368    public final int getLeft() {
9369        return mLeft;
9370    }
9371
9372    /**
9373     * Sets the left position of this view relative to its parent. This method is meant to be called
9374     * by the layout system and should not generally be called otherwise, because the property
9375     * may be changed at any time by the layout.
9376     *
9377     * @param left The bottom of this view, in pixels.
9378     */
9379    public final void setLeft(int left) {
9380        if (left != mLeft) {
9381            updateMatrix();
9382            final boolean matrixIsIdentity = mTransformationInfo == null
9383                    || mTransformationInfo.mMatrixIsIdentity;
9384            if (matrixIsIdentity) {
9385                if (mAttachInfo != null) {
9386                    int minLeft;
9387                    int xLoc;
9388                    if (left < mLeft) {
9389                        minLeft = left;
9390                        xLoc = left - mLeft;
9391                    } else {
9392                        minLeft = mLeft;
9393                        xLoc = 0;
9394                    }
9395                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9396                }
9397            } else {
9398                // Double-invalidation is necessary to capture view's old and new areas
9399                invalidate(true);
9400            }
9401
9402            int oldWidth = mRight - mLeft;
9403            int height = mBottom - mTop;
9404
9405            mLeft = left;
9406            if (mDisplayList != null) {
9407                mDisplayList.setLeft(left);
9408            }
9409
9410            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9411
9412            if (!matrixIsIdentity) {
9413                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9414                    // A change in dimension means an auto-centered pivot point changes, too
9415                    mTransformationInfo.mMatrixDirty = true;
9416                }
9417                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9418                invalidate(true);
9419            }
9420            mBackgroundSizeChanged = true;
9421            invalidateParentIfNeeded();
9422            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9423                // View was rejected last time it was drawn by its parent; this may have changed
9424                invalidateParentIfNeeded();
9425            }
9426        }
9427    }
9428
9429    /**
9430     * Right position of this view relative to its parent.
9431     *
9432     * @return The right edge of this view, in pixels.
9433     */
9434    @ViewDebug.CapturedViewProperty
9435    public final int getRight() {
9436        return mRight;
9437    }
9438
9439    /**
9440     * Sets the right position of this view relative to its parent. This method is meant to be called
9441     * by the layout system and should not generally be called otherwise, because the property
9442     * may be changed at any time by the layout.
9443     *
9444     * @param right The bottom of this view, in pixels.
9445     */
9446    public final void setRight(int right) {
9447        if (right != mRight) {
9448            updateMatrix();
9449            final boolean matrixIsIdentity = mTransformationInfo == null
9450                    || mTransformationInfo.mMatrixIsIdentity;
9451            if (matrixIsIdentity) {
9452                if (mAttachInfo != null) {
9453                    int maxRight;
9454                    if (right < mRight) {
9455                        maxRight = mRight;
9456                    } else {
9457                        maxRight = right;
9458                    }
9459                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9460                }
9461            } else {
9462                // Double-invalidation is necessary to capture view's old and new areas
9463                invalidate(true);
9464            }
9465
9466            int oldWidth = mRight - mLeft;
9467            int height = mBottom - mTop;
9468
9469            mRight = right;
9470            if (mDisplayList != null) {
9471                mDisplayList.setRight(mRight);
9472            }
9473
9474            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9475
9476            if (!matrixIsIdentity) {
9477                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9478                    // A change in dimension means an auto-centered pivot point changes, too
9479                    mTransformationInfo.mMatrixDirty = true;
9480                }
9481                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9482                invalidate(true);
9483            }
9484            mBackgroundSizeChanged = true;
9485            invalidateParentIfNeeded();
9486            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9487                // View was rejected last time it was drawn by its parent; this may have changed
9488                invalidateParentIfNeeded();
9489            }
9490        }
9491    }
9492
9493    /**
9494     * The visual x position of this view, in pixels. This is equivalent to the
9495     * {@link #setTranslationX(float) translationX} property plus the current
9496     * {@link #getLeft() left} property.
9497     *
9498     * @return The visual x position of this view, in pixels.
9499     */
9500    @ViewDebug.ExportedProperty(category = "drawing")
9501    public float getX() {
9502        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9503    }
9504
9505    /**
9506     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9507     * {@link #setTranslationX(float) translationX} property to be the difference between
9508     * the x value passed in and the current {@link #getLeft() left} property.
9509     *
9510     * @param x The visual x position of this view, in pixels.
9511     */
9512    public void setX(float x) {
9513        setTranslationX(x - mLeft);
9514    }
9515
9516    /**
9517     * The visual y position of this view, in pixels. This is equivalent to the
9518     * {@link #setTranslationY(float) translationY} property plus the current
9519     * {@link #getTop() top} property.
9520     *
9521     * @return The visual y position of this view, in pixels.
9522     */
9523    @ViewDebug.ExportedProperty(category = "drawing")
9524    public float getY() {
9525        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9526    }
9527
9528    /**
9529     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9530     * {@link #setTranslationY(float) translationY} property to be the difference between
9531     * the y value passed in and the current {@link #getTop() top} property.
9532     *
9533     * @param y The visual y position of this view, in pixels.
9534     */
9535    public void setY(float y) {
9536        setTranslationY(y - mTop);
9537    }
9538
9539
9540    /**
9541     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9542     * This position is post-layout, in addition to wherever the object's
9543     * layout placed it.
9544     *
9545     * @return The horizontal position of this view relative to its left position, in pixels.
9546     */
9547    @ViewDebug.ExportedProperty(category = "drawing")
9548    public float getTranslationX() {
9549        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9550    }
9551
9552    /**
9553     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9554     * This effectively positions the object post-layout, in addition to wherever the object's
9555     * layout placed it.
9556     *
9557     * @param translationX The horizontal position of this view relative to its left position,
9558     * in pixels.
9559     *
9560     * @attr ref android.R.styleable#View_translationX
9561     */
9562    public void setTranslationX(float translationX) {
9563        ensureTransformationInfo();
9564        final TransformationInfo info = mTransformationInfo;
9565        if (info.mTranslationX != translationX) {
9566            // Double-invalidation is necessary to capture view's old and new areas
9567            invalidateViewProperty(true, false);
9568            info.mTranslationX = translationX;
9569            info.mMatrixDirty = true;
9570            invalidateViewProperty(false, true);
9571            if (mDisplayList != null) {
9572                mDisplayList.setTranslationX(translationX);
9573            }
9574            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9575                // View was rejected last time it was drawn by its parent; this may have changed
9576                invalidateParentIfNeeded();
9577            }
9578        }
9579    }
9580
9581    /**
9582     * The horizontal location of this view relative to its {@link #getTop() top} position.
9583     * This position is post-layout, in addition to wherever the object's
9584     * layout placed it.
9585     *
9586     * @return The vertical position of this view relative to its top position,
9587     * in pixels.
9588     */
9589    @ViewDebug.ExportedProperty(category = "drawing")
9590    public float getTranslationY() {
9591        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9592    }
9593
9594    /**
9595     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9596     * This effectively positions the object post-layout, in addition to wherever the object's
9597     * layout placed it.
9598     *
9599     * @param translationY The vertical position of this view relative to its top position,
9600     * in pixels.
9601     *
9602     * @attr ref android.R.styleable#View_translationY
9603     */
9604    public void setTranslationY(float translationY) {
9605        ensureTransformationInfo();
9606        final TransformationInfo info = mTransformationInfo;
9607        if (info.mTranslationY != translationY) {
9608            invalidateViewProperty(true, false);
9609            info.mTranslationY = translationY;
9610            info.mMatrixDirty = true;
9611            invalidateViewProperty(false, true);
9612            if (mDisplayList != null) {
9613                mDisplayList.setTranslationY(translationY);
9614            }
9615            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9616                // View was rejected last time it was drawn by its parent; this may have changed
9617                invalidateParentIfNeeded();
9618            }
9619        }
9620    }
9621
9622    /**
9623     * Hit rectangle in parent's coordinates
9624     *
9625     * @param outRect The hit rectangle of the view.
9626     */
9627    public void getHitRect(Rect outRect) {
9628        updateMatrix();
9629        final TransformationInfo info = mTransformationInfo;
9630        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9631            outRect.set(mLeft, mTop, mRight, mBottom);
9632        } else {
9633            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9634            tmpRect.set(-info.mPivotX, -info.mPivotY,
9635                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9636            info.mMatrix.mapRect(tmpRect);
9637            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9638                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9639        }
9640    }
9641
9642    /**
9643     * Determines whether the given point, in local coordinates is inside the view.
9644     */
9645    /*package*/ final boolean pointInView(float localX, float localY) {
9646        return localX >= 0 && localX < (mRight - mLeft)
9647                && localY >= 0 && localY < (mBottom - mTop);
9648    }
9649
9650    /**
9651     * Utility method to determine whether the given point, in local coordinates,
9652     * is inside the view, where the area of the view is expanded by the slop factor.
9653     * This method is called while processing touch-move events to determine if the event
9654     * is still within the view.
9655     */
9656    private boolean pointInView(float localX, float localY, float slop) {
9657        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9658                localY < ((mBottom - mTop) + slop);
9659    }
9660
9661    /**
9662     * When a view has focus and the user navigates away from it, the next view is searched for
9663     * starting from the rectangle filled in by this method.
9664     *
9665     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9666     * of the view.  However, if your view maintains some idea of internal selection,
9667     * such as a cursor, or a selected row or column, you should override this method and
9668     * fill in a more specific rectangle.
9669     *
9670     * @param r The rectangle to fill in, in this view's coordinates.
9671     */
9672    public void getFocusedRect(Rect r) {
9673        getDrawingRect(r);
9674    }
9675
9676    /**
9677     * If some part of this view is not clipped by any of its parents, then
9678     * return that area in r in global (root) coordinates. To convert r to local
9679     * coordinates (without taking possible View rotations into account), offset
9680     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9681     * If the view is completely clipped or translated out, return false.
9682     *
9683     * @param r If true is returned, r holds the global coordinates of the
9684     *        visible portion of this view.
9685     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9686     *        between this view and its root. globalOffet may be null.
9687     * @return true if r is non-empty (i.e. part of the view is visible at the
9688     *         root level.
9689     */
9690    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9691        int width = mRight - mLeft;
9692        int height = mBottom - mTop;
9693        if (width > 0 && height > 0) {
9694            r.set(0, 0, width, height);
9695            if (globalOffset != null) {
9696                globalOffset.set(-mScrollX, -mScrollY);
9697            }
9698            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9699        }
9700        return false;
9701    }
9702
9703    public final boolean getGlobalVisibleRect(Rect r) {
9704        return getGlobalVisibleRect(r, null);
9705    }
9706
9707    public final boolean getLocalVisibleRect(Rect r) {
9708        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9709        if (getGlobalVisibleRect(r, offset)) {
9710            r.offset(-offset.x, -offset.y); // make r local
9711            return true;
9712        }
9713        return false;
9714    }
9715
9716    /**
9717     * Offset this view's vertical location by the specified number of pixels.
9718     *
9719     * @param offset the number of pixels to offset the view by
9720     */
9721    public void offsetTopAndBottom(int offset) {
9722        if (offset != 0) {
9723            updateMatrix();
9724            final boolean matrixIsIdentity = mTransformationInfo == null
9725                    || mTransformationInfo.mMatrixIsIdentity;
9726            if (matrixIsIdentity) {
9727                if (mDisplayList != null) {
9728                    invalidateViewProperty(false, false);
9729                } else {
9730                    final ViewParent p = mParent;
9731                    if (p != null && mAttachInfo != null) {
9732                        final Rect r = mAttachInfo.mTmpInvalRect;
9733                        int minTop;
9734                        int maxBottom;
9735                        int yLoc;
9736                        if (offset < 0) {
9737                            minTop = mTop + offset;
9738                            maxBottom = mBottom;
9739                            yLoc = offset;
9740                        } else {
9741                            minTop = mTop;
9742                            maxBottom = mBottom + offset;
9743                            yLoc = 0;
9744                        }
9745                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9746                        p.invalidateChild(this, r);
9747                    }
9748                }
9749            } else {
9750                invalidateViewProperty(false, false);
9751            }
9752
9753            mTop += offset;
9754            mBottom += offset;
9755            if (mDisplayList != null) {
9756                mDisplayList.offsetTopBottom(offset);
9757                invalidateViewProperty(false, false);
9758            } else {
9759                if (!matrixIsIdentity) {
9760                    invalidateViewProperty(false, true);
9761                }
9762                invalidateParentIfNeeded();
9763            }
9764        }
9765    }
9766
9767    /**
9768     * Offset this view's horizontal location by the specified amount of pixels.
9769     *
9770     * @param offset the numer of pixels to offset the view by
9771     */
9772    public void offsetLeftAndRight(int offset) {
9773        if (offset != 0) {
9774            updateMatrix();
9775            final boolean matrixIsIdentity = mTransformationInfo == null
9776                    || mTransformationInfo.mMatrixIsIdentity;
9777            if (matrixIsIdentity) {
9778                if (mDisplayList != null) {
9779                    invalidateViewProperty(false, false);
9780                } else {
9781                    final ViewParent p = mParent;
9782                    if (p != null && mAttachInfo != null) {
9783                        final Rect r = mAttachInfo.mTmpInvalRect;
9784                        int minLeft;
9785                        int maxRight;
9786                        if (offset < 0) {
9787                            minLeft = mLeft + offset;
9788                            maxRight = mRight;
9789                        } else {
9790                            minLeft = mLeft;
9791                            maxRight = mRight + offset;
9792                        }
9793                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9794                        p.invalidateChild(this, r);
9795                    }
9796                }
9797            } else {
9798                invalidateViewProperty(false, false);
9799            }
9800
9801            mLeft += offset;
9802            mRight += offset;
9803            if (mDisplayList != null) {
9804                mDisplayList.offsetLeftRight(offset);
9805                invalidateViewProperty(false, false);
9806            } else {
9807                if (!matrixIsIdentity) {
9808                    invalidateViewProperty(false, true);
9809                }
9810                invalidateParentIfNeeded();
9811            }
9812        }
9813    }
9814
9815    /**
9816     * Get the LayoutParams associated with this view. All views should have
9817     * layout parameters. These supply parameters to the <i>parent</i> of this
9818     * view specifying how it should be arranged. There are many subclasses of
9819     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9820     * of ViewGroup that are responsible for arranging their children.
9821     *
9822     * This method may return null if this View is not attached to a parent
9823     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9824     * was not invoked successfully. When a View is attached to a parent
9825     * ViewGroup, this method must not return null.
9826     *
9827     * @return The LayoutParams associated with this view, or null if no
9828     *         parameters have been set yet
9829     */
9830    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9831    public ViewGroup.LayoutParams getLayoutParams() {
9832        return mLayoutParams;
9833    }
9834
9835    /**
9836     * Set the layout parameters associated with this view. These supply
9837     * parameters to the <i>parent</i> of this view specifying how it should be
9838     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9839     * correspond to the different subclasses of ViewGroup that are responsible
9840     * for arranging their children.
9841     *
9842     * @param params The layout parameters for this view, cannot be null
9843     */
9844    public void setLayoutParams(ViewGroup.LayoutParams params) {
9845        if (params == null) {
9846            throw new NullPointerException("Layout parameters cannot be null");
9847        }
9848        mLayoutParams = params;
9849        if (mParent instanceof ViewGroup) {
9850            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9851        }
9852        requestLayout();
9853    }
9854
9855    /**
9856     * Set the scrolled position of your view. This will cause a call to
9857     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9858     * invalidated.
9859     * @param x the x position to scroll to
9860     * @param y the y position to scroll to
9861     */
9862    public void scrollTo(int x, int y) {
9863        if (mScrollX != x || mScrollY != y) {
9864            int oldX = mScrollX;
9865            int oldY = mScrollY;
9866            mScrollX = x;
9867            mScrollY = y;
9868            invalidateParentCaches();
9869            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9870            if (!awakenScrollBars()) {
9871                postInvalidateOnAnimation();
9872            }
9873        }
9874    }
9875
9876    /**
9877     * Move the scrolled position of your view. This will cause a call to
9878     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9879     * invalidated.
9880     * @param x the amount of pixels to scroll by horizontally
9881     * @param y the amount of pixels to scroll by vertically
9882     */
9883    public void scrollBy(int x, int y) {
9884        scrollTo(mScrollX + x, mScrollY + y);
9885    }
9886
9887    /**
9888     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9889     * animation to fade the scrollbars out after a default delay. If a subclass
9890     * provides animated scrolling, the start delay should equal the duration
9891     * of the scrolling animation.</p>
9892     *
9893     * <p>The animation starts only if at least one of the scrollbars is
9894     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9895     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9896     * this method returns true, and false otherwise. If the animation is
9897     * started, this method calls {@link #invalidate()}; in that case the
9898     * caller should not call {@link #invalidate()}.</p>
9899     *
9900     * <p>This method should be invoked every time a subclass directly updates
9901     * the scroll parameters.</p>
9902     *
9903     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9904     * and {@link #scrollTo(int, int)}.</p>
9905     *
9906     * @return true if the animation is played, false otherwise
9907     *
9908     * @see #awakenScrollBars(int)
9909     * @see #scrollBy(int, int)
9910     * @see #scrollTo(int, int)
9911     * @see #isHorizontalScrollBarEnabled()
9912     * @see #isVerticalScrollBarEnabled()
9913     * @see #setHorizontalScrollBarEnabled(boolean)
9914     * @see #setVerticalScrollBarEnabled(boolean)
9915     */
9916    protected boolean awakenScrollBars() {
9917        return mScrollCache != null &&
9918                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9919    }
9920
9921    /**
9922     * Trigger the scrollbars to draw.
9923     * This method differs from awakenScrollBars() only in its default duration.
9924     * initialAwakenScrollBars() will show the scroll bars for longer than
9925     * usual to give the user more of a chance to notice them.
9926     *
9927     * @return true if the animation is played, false otherwise.
9928     */
9929    private boolean initialAwakenScrollBars() {
9930        return mScrollCache != null &&
9931                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9932    }
9933
9934    /**
9935     * <p>
9936     * Trigger the scrollbars to draw. When invoked this method starts an
9937     * animation to fade the scrollbars out after a fixed delay. If a subclass
9938     * provides animated scrolling, the start delay should equal the duration of
9939     * the scrolling animation.
9940     * </p>
9941     *
9942     * <p>
9943     * The animation starts only if at least one of the scrollbars is enabled,
9944     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9945     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9946     * this method returns true, and false otherwise. If the animation is
9947     * started, this method calls {@link #invalidate()}; in that case the caller
9948     * should not call {@link #invalidate()}.
9949     * </p>
9950     *
9951     * <p>
9952     * This method should be invoked everytime a subclass directly updates the
9953     * scroll parameters.
9954     * </p>
9955     *
9956     * @param startDelay the delay, in milliseconds, after which the animation
9957     *        should start; when the delay is 0, the animation starts
9958     *        immediately
9959     * @return true if the animation is played, false otherwise
9960     *
9961     * @see #scrollBy(int, int)
9962     * @see #scrollTo(int, int)
9963     * @see #isHorizontalScrollBarEnabled()
9964     * @see #isVerticalScrollBarEnabled()
9965     * @see #setHorizontalScrollBarEnabled(boolean)
9966     * @see #setVerticalScrollBarEnabled(boolean)
9967     */
9968    protected boolean awakenScrollBars(int startDelay) {
9969        return awakenScrollBars(startDelay, true);
9970    }
9971
9972    /**
9973     * <p>
9974     * Trigger the scrollbars to draw. When invoked this method starts an
9975     * animation to fade the scrollbars out after a fixed delay. If a subclass
9976     * provides animated scrolling, the start delay should equal the duration of
9977     * the scrolling animation.
9978     * </p>
9979     *
9980     * <p>
9981     * The animation starts only if at least one of the scrollbars is enabled,
9982     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9983     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9984     * this method returns true, and false otherwise. If the animation is
9985     * started, this method calls {@link #invalidate()} if the invalidate parameter
9986     * is set to true; in that case the caller
9987     * should not call {@link #invalidate()}.
9988     * </p>
9989     *
9990     * <p>
9991     * This method should be invoked everytime a subclass directly updates the
9992     * scroll parameters.
9993     * </p>
9994     *
9995     * @param startDelay the delay, in milliseconds, after which the animation
9996     *        should start; when the delay is 0, the animation starts
9997     *        immediately
9998     *
9999     * @param invalidate Wheter this method should call invalidate
10000     *
10001     * @return true if the animation is played, false otherwise
10002     *
10003     * @see #scrollBy(int, int)
10004     * @see #scrollTo(int, int)
10005     * @see #isHorizontalScrollBarEnabled()
10006     * @see #isVerticalScrollBarEnabled()
10007     * @see #setHorizontalScrollBarEnabled(boolean)
10008     * @see #setVerticalScrollBarEnabled(boolean)
10009     */
10010    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10011        final ScrollabilityCache scrollCache = mScrollCache;
10012
10013        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10014            return false;
10015        }
10016
10017        if (scrollCache.scrollBar == null) {
10018            scrollCache.scrollBar = new ScrollBarDrawable();
10019        }
10020
10021        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10022
10023            if (invalidate) {
10024                // Invalidate to show the scrollbars
10025                postInvalidateOnAnimation();
10026            }
10027
10028            if (scrollCache.state == ScrollabilityCache.OFF) {
10029                // FIXME: this is copied from WindowManagerService.
10030                // We should get this value from the system when it
10031                // is possible to do so.
10032                final int KEY_REPEAT_FIRST_DELAY = 750;
10033                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10034            }
10035
10036            // Tell mScrollCache when we should start fading. This may
10037            // extend the fade start time if one was already scheduled
10038            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10039            scrollCache.fadeStartTime = fadeStartTime;
10040            scrollCache.state = ScrollabilityCache.ON;
10041
10042            // Schedule our fader to run, unscheduling any old ones first
10043            if (mAttachInfo != null) {
10044                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10045                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10046            }
10047
10048            return true;
10049        }
10050
10051        return false;
10052    }
10053
10054    /**
10055     * Do not invalidate views which are not visible and which are not running an animation. They
10056     * will not get drawn and they should not set dirty flags as if they will be drawn
10057     */
10058    private boolean skipInvalidate() {
10059        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10060                (!(mParent instanceof ViewGroup) ||
10061                        !((ViewGroup) mParent).isViewTransitioning(this));
10062    }
10063    /**
10064     * Mark the area defined by dirty as needing to be drawn. If the view is
10065     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10066     * in the future. This must be called from a UI thread. To call from a non-UI
10067     * thread, call {@link #postInvalidate()}.
10068     *
10069     * WARNING: This method is destructive to dirty.
10070     * @param dirty the rectangle representing the bounds of the dirty region
10071     */
10072    public void invalidate(Rect dirty) {
10073        if (skipInvalidate()) {
10074            return;
10075        }
10076        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10077                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
10078                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
10079            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10080            mPrivateFlags |= INVALIDATED;
10081            mPrivateFlags |= DIRTY;
10082            final ViewParent p = mParent;
10083            final AttachInfo ai = mAttachInfo;
10084            //noinspection PointlessBooleanExpression,ConstantConditions
10085            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10086                if (p != null && ai != null && ai.mHardwareAccelerated) {
10087                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10088                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10089                    p.invalidateChild(this, null);
10090                    return;
10091                }
10092            }
10093            if (p != null && ai != null) {
10094                final int scrollX = mScrollX;
10095                final int scrollY = mScrollY;
10096                final Rect r = ai.mTmpInvalRect;
10097                r.set(dirty.left - scrollX, dirty.top - scrollY,
10098                        dirty.right - scrollX, dirty.bottom - scrollY);
10099                mParent.invalidateChild(this, r);
10100            }
10101        }
10102    }
10103
10104    /**
10105     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10106     * The coordinates of the dirty rect are relative to the view.
10107     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10108     * will be called at some point in the future. This must be called from
10109     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10110     * @param l the left position of the dirty region
10111     * @param t the top position of the dirty region
10112     * @param r the right position of the dirty region
10113     * @param b the bottom position of the dirty region
10114     */
10115    public void invalidate(int l, int t, int r, int b) {
10116        if (skipInvalidate()) {
10117            return;
10118        }
10119        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10120                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
10121                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
10122            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10123            mPrivateFlags |= INVALIDATED;
10124            mPrivateFlags |= DIRTY;
10125            final ViewParent p = mParent;
10126            final AttachInfo ai = mAttachInfo;
10127            //noinspection PointlessBooleanExpression,ConstantConditions
10128            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10129                if (p != null && ai != null && ai.mHardwareAccelerated) {
10130                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10131                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10132                    p.invalidateChild(this, null);
10133                    return;
10134                }
10135            }
10136            if (p != null && ai != null && l < r && t < b) {
10137                final int scrollX = mScrollX;
10138                final int scrollY = mScrollY;
10139                final Rect tmpr = ai.mTmpInvalRect;
10140                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10141                p.invalidateChild(this, tmpr);
10142            }
10143        }
10144    }
10145
10146    /**
10147     * Invalidate the whole view. If the view is visible,
10148     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10149     * the future. This must be called from a UI thread. To call from a non-UI thread,
10150     * call {@link #postInvalidate()}.
10151     */
10152    public void invalidate() {
10153        invalidate(true);
10154    }
10155
10156    /**
10157     * This is where the invalidate() work actually happens. A full invalidate()
10158     * causes the drawing cache to be invalidated, but this function can be called with
10159     * invalidateCache set to false to skip that invalidation step for cases that do not
10160     * need it (for example, a component that remains at the same dimensions with the same
10161     * content).
10162     *
10163     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10164     * well. This is usually true for a full invalidate, but may be set to false if the
10165     * View's contents or dimensions have not changed.
10166     */
10167    void invalidate(boolean invalidateCache) {
10168        if (skipInvalidate()) {
10169            return;
10170        }
10171        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10172                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
10173                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
10174            mLastIsOpaque = isOpaque();
10175            mPrivateFlags &= ~DRAWN;
10176            mPrivateFlags |= DIRTY;
10177            if (invalidateCache) {
10178                mPrivateFlags |= INVALIDATED;
10179                mPrivateFlags &= ~DRAWING_CACHE_VALID;
10180            }
10181            final AttachInfo ai = mAttachInfo;
10182            final ViewParent p = mParent;
10183            //noinspection PointlessBooleanExpression,ConstantConditions
10184            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10185                if (p != null && ai != null && ai.mHardwareAccelerated) {
10186                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10187                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10188                    p.invalidateChild(this, null);
10189                    return;
10190                }
10191            }
10192
10193            if (p != null && ai != null) {
10194                final Rect r = ai.mTmpInvalRect;
10195                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10196                // Don't call invalidate -- we don't want to internally scroll
10197                // our own bounds
10198                p.invalidateChild(this, r);
10199            }
10200        }
10201    }
10202
10203    /**
10204     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10205     * set any flags or handle all of the cases handled by the default invalidation methods.
10206     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10207     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10208     * walk up the hierarchy, transforming the dirty rect as necessary.
10209     *
10210     * The method also handles normal invalidation logic if display list properties are not
10211     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10212     * backup approach, to handle these cases used in the various property-setting methods.
10213     *
10214     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10215     * are not being used in this view
10216     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10217     * list properties are not being used in this view
10218     */
10219    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10220        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10221            if (invalidateParent) {
10222                invalidateParentCaches();
10223            }
10224            if (forceRedraw) {
10225                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10226            }
10227            invalidate(false);
10228        } else {
10229            final AttachInfo ai = mAttachInfo;
10230            final ViewParent p = mParent;
10231            if (p != null && ai != null) {
10232                final Rect r = ai.mTmpInvalRect;
10233                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10234                if (mParent instanceof ViewGroup) {
10235                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10236                } else {
10237                    mParent.invalidateChild(this, r);
10238                }
10239            }
10240        }
10241    }
10242
10243    /**
10244     * Utility method to transform a given Rect by the current matrix of this view.
10245     */
10246    void transformRect(final Rect rect) {
10247        if (!getMatrix().isIdentity()) {
10248            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10249            boundingRect.set(rect);
10250            getMatrix().mapRect(boundingRect);
10251            rect.set((int) (boundingRect.left - 0.5f),
10252                    (int) (boundingRect.top - 0.5f),
10253                    (int) (boundingRect.right + 0.5f),
10254                    (int) (boundingRect.bottom + 0.5f));
10255        }
10256    }
10257
10258    /**
10259     * Used to indicate that the parent of this view should clear its caches. This functionality
10260     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10261     * which is necessary when various parent-managed properties of the view change, such as
10262     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10263     * clears the parent caches and does not causes an invalidate event.
10264     *
10265     * @hide
10266     */
10267    protected void invalidateParentCaches() {
10268        if (mParent instanceof View) {
10269            ((View) mParent).mPrivateFlags |= INVALIDATED;
10270        }
10271    }
10272
10273    /**
10274     * Used to indicate that the parent of this view should be invalidated. This functionality
10275     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10276     * which is necessary when various parent-managed properties of the view change, such as
10277     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10278     * an invalidation event to the parent.
10279     *
10280     * @hide
10281     */
10282    protected void invalidateParentIfNeeded() {
10283        if (isHardwareAccelerated() && mParent instanceof View) {
10284            ((View) mParent).invalidate(true);
10285        }
10286    }
10287
10288    /**
10289     * Indicates whether this View is opaque. An opaque View guarantees that it will
10290     * draw all the pixels overlapping its bounds using a fully opaque color.
10291     *
10292     * Subclasses of View should override this method whenever possible to indicate
10293     * whether an instance is opaque. Opaque Views are treated in a special way by
10294     * the View hierarchy, possibly allowing it to perform optimizations during
10295     * invalidate/draw passes.
10296     *
10297     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10298     */
10299    @ViewDebug.ExportedProperty(category = "drawing")
10300    public boolean isOpaque() {
10301        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10302                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10303                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10304    }
10305
10306    /**
10307     * @hide
10308     */
10309    protected void computeOpaqueFlags() {
10310        // Opaque if:
10311        //   - Has a background
10312        //   - Background is opaque
10313        //   - Doesn't have scrollbars or scrollbars are inside overlay
10314
10315        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10316            mPrivateFlags |= OPAQUE_BACKGROUND;
10317        } else {
10318            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10319        }
10320
10321        final int flags = mViewFlags;
10322        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10323                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10324            mPrivateFlags |= OPAQUE_SCROLLBARS;
10325        } else {
10326            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10327        }
10328    }
10329
10330    /**
10331     * @hide
10332     */
10333    protected boolean hasOpaqueScrollbars() {
10334        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10335    }
10336
10337    /**
10338     * @return A handler associated with the thread running the View. This
10339     * handler can be used to pump events in the UI events queue.
10340     */
10341    public Handler getHandler() {
10342        if (mAttachInfo != null) {
10343            return mAttachInfo.mHandler;
10344        }
10345        return null;
10346    }
10347
10348    /**
10349     * Gets the view root associated with the View.
10350     * @return The view root, or null if none.
10351     * @hide
10352     */
10353    public ViewRootImpl getViewRootImpl() {
10354        if (mAttachInfo != null) {
10355            return mAttachInfo.mViewRootImpl;
10356        }
10357        return null;
10358    }
10359
10360    /**
10361     * <p>Causes the Runnable to be added to the message queue.
10362     * The runnable will be run on the user interface thread.</p>
10363     *
10364     * <p>This method can be invoked from outside of the UI thread
10365     * only when this View is attached to a window.</p>
10366     *
10367     * @param action The Runnable that will be executed.
10368     *
10369     * @return Returns true if the Runnable was successfully placed in to the
10370     *         message queue.  Returns false on failure, usually because the
10371     *         looper processing the message queue is exiting.
10372     *
10373     * @see #postDelayed
10374     * @see #removeCallbacks
10375     */
10376    public boolean post(Runnable action) {
10377        final AttachInfo attachInfo = mAttachInfo;
10378        if (attachInfo != null) {
10379            return attachInfo.mHandler.post(action);
10380        }
10381        // Assume that post will succeed later
10382        ViewRootImpl.getRunQueue().post(action);
10383        return true;
10384    }
10385
10386    /**
10387     * <p>Causes the Runnable to be added to the message queue, to be run
10388     * after the specified amount of time elapses.
10389     * The runnable will be run on the user interface thread.</p>
10390     *
10391     * <p>This method can be invoked from outside of the UI thread
10392     * only when this View is attached to a window.</p>
10393     *
10394     * @param action The Runnable that will be executed.
10395     * @param delayMillis The delay (in milliseconds) until the Runnable
10396     *        will be executed.
10397     *
10398     * @return true if the Runnable was successfully placed in to the
10399     *         message queue.  Returns false on failure, usually because the
10400     *         looper processing the message queue is exiting.  Note that a
10401     *         result of true does not mean the Runnable will be processed --
10402     *         if the looper is quit before the delivery time of the message
10403     *         occurs then the message will be dropped.
10404     *
10405     * @see #post
10406     * @see #removeCallbacks
10407     */
10408    public boolean postDelayed(Runnable action, long delayMillis) {
10409        final AttachInfo attachInfo = mAttachInfo;
10410        if (attachInfo != null) {
10411            return attachInfo.mHandler.postDelayed(action, delayMillis);
10412        }
10413        // Assume that post will succeed later
10414        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10415        return true;
10416    }
10417
10418    /**
10419     * <p>Causes the Runnable to execute on the next animation time step.
10420     * The runnable will be run on the user interface thread.</p>
10421     *
10422     * <p>This method can be invoked from outside of the UI thread
10423     * only when this View is attached to a window.</p>
10424     *
10425     * @param action The Runnable that will be executed.
10426     *
10427     * @see #postOnAnimationDelayed
10428     * @see #removeCallbacks
10429     */
10430    public void postOnAnimation(Runnable action) {
10431        final AttachInfo attachInfo = mAttachInfo;
10432        if (attachInfo != null) {
10433            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10434                    Choreographer.CALLBACK_ANIMATION, action, null);
10435        } else {
10436            // Assume that post will succeed later
10437            ViewRootImpl.getRunQueue().post(action);
10438        }
10439    }
10440
10441    /**
10442     * <p>Causes the Runnable to execute on the next animation time step,
10443     * after the specified amount of time elapses.
10444     * The runnable will be run on the user interface thread.</p>
10445     *
10446     * <p>This method can be invoked from outside of the UI thread
10447     * only when this View is attached to a window.</p>
10448     *
10449     * @param action The Runnable that will be executed.
10450     * @param delayMillis The delay (in milliseconds) until the Runnable
10451     *        will be executed.
10452     *
10453     * @see #postOnAnimation
10454     * @see #removeCallbacks
10455     */
10456    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10457        final AttachInfo attachInfo = mAttachInfo;
10458        if (attachInfo != null) {
10459            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10460                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10461        } else {
10462            // Assume that post will succeed later
10463            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10464        }
10465    }
10466
10467    /**
10468     * <p>Removes the specified Runnable from the message queue.</p>
10469     *
10470     * <p>This method can be invoked from outside of the UI thread
10471     * only when this View is attached to a window.</p>
10472     *
10473     * @param action The Runnable to remove from the message handling queue
10474     *
10475     * @return true if this view could ask the Handler to remove the Runnable,
10476     *         false otherwise. When the returned value is true, the Runnable
10477     *         may or may not have been actually removed from the message queue
10478     *         (for instance, if the Runnable was not in the queue already.)
10479     *
10480     * @see #post
10481     * @see #postDelayed
10482     * @see #postOnAnimation
10483     * @see #postOnAnimationDelayed
10484     */
10485    public boolean removeCallbacks(Runnable action) {
10486        if (action != null) {
10487            final AttachInfo attachInfo = mAttachInfo;
10488            if (attachInfo != null) {
10489                attachInfo.mHandler.removeCallbacks(action);
10490                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10491                        Choreographer.CALLBACK_ANIMATION, action, null);
10492            } else {
10493                // Assume that post will succeed later
10494                ViewRootImpl.getRunQueue().removeCallbacks(action);
10495            }
10496        }
10497        return true;
10498    }
10499
10500    /**
10501     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10502     * Use this to invalidate the View from a non-UI thread.</p>
10503     *
10504     * <p>This method can be invoked from outside of the UI thread
10505     * only when this View is attached to a window.</p>
10506     *
10507     * @see #invalidate()
10508     * @see #postInvalidateDelayed(long)
10509     */
10510    public void postInvalidate() {
10511        postInvalidateDelayed(0);
10512    }
10513
10514    /**
10515     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10516     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10517     *
10518     * <p>This method can be invoked from outside of the UI thread
10519     * only when this View is attached to a window.</p>
10520     *
10521     * @param left The left coordinate of the rectangle to invalidate.
10522     * @param top The top coordinate of the rectangle to invalidate.
10523     * @param right The right coordinate of the rectangle to invalidate.
10524     * @param bottom The bottom coordinate of the rectangle to invalidate.
10525     *
10526     * @see #invalidate(int, int, int, int)
10527     * @see #invalidate(Rect)
10528     * @see #postInvalidateDelayed(long, int, int, int, int)
10529     */
10530    public void postInvalidate(int left, int top, int right, int bottom) {
10531        postInvalidateDelayed(0, left, top, right, bottom);
10532    }
10533
10534    /**
10535     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10536     * loop. Waits for the specified amount of time.</p>
10537     *
10538     * <p>This method can be invoked from outside of the UI thread
10539     * only when this View is attached to a window.</p>
10540     *
10541     * @param delayMilliseconds the duration in milliseconds to delay the
10542     *         invalidation by
10543     *
10544     * @see #invalidate()
10545     * @see #postInvalidate()
10546     */
10547    public void postInvalidateDelayed(long delayMilliseconds) {
10548        // We try only with the AttachInfo because there's no point in invalidating
10549        // if we are not attached to our window
10550        final AttachInfo attachInfo = mAttachInfo;
10551        if (attachInfo != null) {
10552            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10553        }
10554    }
10555
10556    /**
10557     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10558     * through the event loop. Waits for the specified amount of time.</p>
10559     *
10560     * <p>This method can be invoked from outside of the UI thread
10561     * only when this View is attached to a window.</p>
10562     *
10563     * @param delayMilliseconds the duration in milliseconds to delay the
10564     *         invalidation by
10565     * @param left The left coordinate of the rectangle to invalidate.
10566     * @param top The top coordinate of the rectangle to invalidate.
10567     * @param right The right coordinate of the rectangle to invalidate.
10568     * @param bottom The bottom coordinate of the rectangle to invalidate.
10569     *
10570     * @see #invalidate(int, int, int, int)
10571     * @see #invalidate(Rect)
10572     * @see #postInvalidate(int, int, int, int)
10573     */
10574    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10575            int right, int bottom) {
10576
10577        // We try only with the AttachInfo because there's no point in invalidating
10578        // if we are not attached to our window
10579        final AttachInfo attachInfo = mAttachInfo;
10580        if (attachInfo != null) {
10581            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10582            info.target = this;
10583            info.left = left;
10584            info.top = top;
10585            info.right = right;
10586            info.bottom = bottom;
10587
10588            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10589        }
10590    }
10591
10592    /**
10593     * <p>Cause an invalidate to happen on the next animation time step, typically the
10594     * next display frame.</p>
10595     *
10596     * <p>This method can be invoked from outside of the UI thread
10597     * only when this View is attached to a window.</p>
10598     *
10599     * @see #invalidate()
10600     */
10601    public void postInvalidateOnAnimation() {
10602        // We try only with the AttachInfo because there's no point in invalidating
10603        // if we are not attached to our window
10604        final AttachInfo attachInfo = mAttachInfo;
10605        if (attachInfo != null) {
10606            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10607        }
10608    }
10609
10610    /**
10611     * <p>Cause an invalidate of the specified area to happen on the next animation
10612     * time step, typically the next display frame.</p>
10613     *
10614     * <p>This method can be invoked from outside of the UI thread
10615     * only when this View is attached to a window.</p>
10616     *
10617     * @param left The left coordinate of the rectangle to invalidate.
10618     * @param top The top coordinate of the rectangle to invalidate.
10619     * @param right The right coordinate of the rectangle to invalidate.
10620     * @param bottom The bottom coordinate of the rectangle to invalidate.
10621     *
10622     * @see #invalidate(int, int, int, int)
10623     * @see #invalidate(Rect)
10624     */
10625    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10626        // We try only with the AttachInfo because there's no point in invalidating
10627        // if we are not attached to our window
10628        final AttachInfo attachInfo = mAttachInfo;
10629        if (attachInfo != null) {
10630            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10631            info.target = this;
10632            info.left = left;
10633            info.top = top;
10634            info.right = right;
10635            info.bottom = bottom;
10636
10637            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10638        }
10639    }
10640
10641    /**
10642     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10643     * This event is sent at most once every
10644     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10645     */
10646    private void postSendViewScrolledAccessibilityEventCallback() {
10647        if (mSendViewScrolledAccessibilityEvent == null) {
10648            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10649        }
10650        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10651            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10652            postDelayed(mSendViewScrolledAccessibilityEvent,
10653                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10654        }
10655    }
10656
10657    /**
10658     * Called by a parent to request that a child update its values for mScrollX
10659     * and mScrollY if necessary. This will typically be done if the child is
10660     * animating a scroll using a {@link android.widget.Scroller Scroller}
10661     * object.
10662     */
10663    public void computeScroll() {
10664    }
10665
10666    /**
10667     * <p>Indicate whether the horizontal edges are faded when the view is
10668     * scrolled horizontally.</p>
10669     *
10670     * @return true if the horizontal edges should are faded on scroll, false
10671     *         otherwise
10672     *
10673     * @see #setHorizontalFadingEdgeEnabled(boolean)
10674     *
10675     * @attr ref android.R.styleable#View_requiresFadingEdge
10676     */
10677    public boolean isHorizontalFadingEdgeEnabled() {
10678        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10679    }
10680
10681    /**
10682     * <p>Define whether the horizontal edges should be faded when this view
10683     * is scrolled horizontally.</p>
10684     *
10685     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10686     *                                    be faded when the view is scrolled
10687     *                                    horizontally
10688     *
10689     * @see #isHorizontalFadingEdgeEnabled()
10690     *
10691     * @attr ref android.R.styleable#View_requiresFadingEdge
10692     */
10693    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10694        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10695            if (horizontalFadingEdgeEnabled) {
10696                initScrollCache();
10697            }
10698
10699            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10700        }
10701    }
10702
10703    /**
10704     * <p>Indicate whether the vertical edges are faded when the view is
10705     * scrolled horizontally.</p>
10706     *
10707     * @return true if the vertical edges should are faded on scroll, false
10708     *         otherwise
10709     *
10710     * @see #setVerticalFadingEdgeEnabled(boolean)
10711     *
10712     * @attr ref android.R.styleable#View_requiresFadingEdge
10713     */
10714    public boolean isVerticalFadingEdgeEnabled() {
10715        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10716    }
10717
10718    /**
10719     * <p>Define whether the vertical edges should be faded when this view
10720     * is scrolled vertically.</p>
10721     *
10722     * @param verticalFadingEdgeEnabled true if the vertical edges should
10723     *                                  be faded when the view is scrolled
10724     *                                  vertically
10725     *
10726     * @see #isVerticalFadingEdgeEnabled()
10727     *
10728     * @attr ref android.R.styleable#View_requiresFadingEdge
10729     */
10730    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10731        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10732            if (verticalFadingEdgeEnabled) {
10733                initScrollCache();
10734            }
10735
10736            mViewFlags ^= FADING_EDGE_VERTICAL;
10737        }
10738    }
10739
10740    /**
10741     * Returns the strength, or intensity, of the top faded edge. The strength is
10742     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10743     * returns 0.0 or 1.0 but no value in between.
10744     *
10745     * Subclasses should override this method to provide a smoother fade transition
10746     * when scrolling occurs.
10747     *
10748     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10749     */
10750    protected float getTopFadingEdgeStrength() {
10751        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10752    }
10753
10754    /**
10755     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10756     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10757     * returns 0.0 or 1.0 but no value in between.
10758     *
10759     * Subclasses should override this method to provide a smoother fade transition
10760     * when scrolling occurs.
10761     *
10762     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10763     */
10764    protected float getBottomFadingEdgeStrength() {
10765        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10766                computeVerticalScrollRange() ? 1.0f : 0.0f;
10767    }
10768
10769    /**
10770     * Returns the strength, or intensity, of the left faded edge. The strength is
10771     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10772     * returns 0.0 or 1.0 but no value in between.
10773     *
10774     * Subclasses should override this method to provide a smoother fade transition
10775     * when scrolling occurs.
10776     *
10777     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10778     */
10779    protected float getLeftFadingEdgeStrength() {
10780        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10781    }
10782
10783    /**
10784     * Returns the strength, or intensity, of the right faded edge. The strength is
10785     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10786     * returns 0.0 or 1.0 but no value in between.
10787     *
10788     * Subclasses should override this method to provide a smoother fade transition
10789     * when scrolling occurs.
10790     *
10791     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10792     */
10793    protected float getRightFadingEdgeStrength() {
10794        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10795                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10796    }
10797
10798    /**
10799     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10800     * scrollbar is not drawn by default.</p>
10801     *
10802     * @return true if the horizontal scrollbar should be painted, false
10803     *         otherwise
10804     *
10805     * @see #setHorizontalScrollBarEnabled(boolean)
10806     */
10807    public boolean isHorizontalScrollBarEnabled() {
10808        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10809    }
10810
10811    /**
10812     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10813     * scrollbar is not drawn by default.</p>
10814     *
10815     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10816     *                                   be painted
10817     *
10818     * @see #isHorizontalScrollBarEnabled()
10819     */
10820    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10821        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10822            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10823            computeOpaqueFlags();
10824            resolvePadding();
10825        }
10826    }
10827
10828    /**
10829     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10830     * scrollbar is not drawn by default.</p>
10831     *
10832     * @return true if the vertical scrollbar should be painted, false
10833     *         otherwise
10834     *
10835     * @see #setVerticalScrollBarEnabled(boolean)
10836     */
10837    public boolean isVerticalScrollBarEnabled() {
10838        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10839    }
10840
10841    /**
10842     * <p>Define whether the vertical scrollbar should be drawn or not. The
10843     * scrollbar is not drawn by default.</p>
10844     *
10845     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10846     *                                 be painted
10847     *
10848     * @see #isVerticalScrollBarEnabled()
10849     */
10850    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10851        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10852            mViewFlags ^= SCROLLBARS_VERTICAL;
10853            computeOpaqueFlags();
10854            resolvePadding();
10855        }
10856    }
10857
10858    /**
10859     * @hide
10860     */
10861    protected void recomputePadding() {
10862        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10863    }
10864
10865    /**
10866     * Define whether scrollbars will fade when the view is not scrolling.
10867     *
10868     * @param fadeScrollbars wheter to enable fading
10869     *
10870     * @attr ref android.R.styleable#View_fadeScrollbars
10871     */
10872    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10873        initScrollCache();
10874        final ScrollabilityCache scrollabilityCache = mScrollCache;
10875        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10876        if (fadeScrollbars) {
10877            scrollabilityCache.state = ScrollabilityCache.OFF;
10878        } else {
10879            scrollabilityCache.state = ScrollabilityCache.ON;
10880        }
10881    }
10882
10883    /**
10884     *
10885     * Returns true if scrollbars will fade when this view is not scrolling
10886     *
10887     * @return true if scrollbar fading is enabled
10888     *
10889     * @attr ref android.R.styleable#View_fadeScrollbars
10890     */
10891    public boolean isScrollbarFadingEnabled() {
10892        return mScrollCache != null && mScrollCache.fadeScrollBars;
10893    }
10894
10895    /**
10896     *
10897     * Returns the delay before scrollbars fade.
10898     *
10899     * @return the delay before scrollbars fade
10900     *
10901     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10902     */
10903    public int getScrollBarDefaultDelayBeforeFade() {
10904        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10905                mScrollCache.scrollBarDefaultDelayBeforeFade;
10906    }
10907
10908    /**
10909     * Define the delay before scrollbars fade.
10910     *
10911     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10912     *
10913     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10914     */
10915    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10916        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10917    }
10918
10919    /**
10920     *
10921     * Returns the scrollbar fade duration.
10922     *
10923     * @return the scrollbar fade duration
10924     *
10925     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10926     */
10927    public int getScrollBarFadeDuration() {
10928        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10929                mScrollCache.scrollBarFadeDuration;
10930    }
10931
10932    /**
10933     * Define the scrollbar fade duration.
10934     *
10935     * @param scrollBarFadeDuration - the scrollbar fade duration
10936     *
10937     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10938     */
10939    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10940        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10941    }
10942
10943    /**
10944     *
10945     * Returns the scrollbar size.
10946     *
10947     * @return the scrollbar size
10948     *
10949     * @attr ref android.R.styleable#View_scrollbarSize
10950     */
10951    public int getScrollBarSize() {
10952        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10953                mScrollCache.scrollBarSize;
10954    }
10955
10956    /**
10957     * Define the scrollbar size.
10958     *
10959     * @param scrollBarSize - the scrollbar size
10960     *
10961     * @attr ref android.R.styleable#View_scrollbarSize
10962     */
10963    public void setScrollBarSize(int scrollBarSize) {
10964        getScrollCache().scrollBarSize = scrollBarSize;
10965    }
10966
10967    /**
10968     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10969     * inset. When inset, they add to the padding of the view. And the scrollbars
10970     * can be drawn inside the padding area or on the edge of the view. For example,
10971     * if a view has a background drawable and you want to draw the scrollbars
10972     * inside the padding specified by the drawable, you can use
10973     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10974     * appear at the edge of the view, ignoring the padding, then you can use
10975     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10976     * @param style the style of the scrollbars. Should be one of
10977     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10978     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10979     * @see #SCROLLBARS_INSIDE_OVERLAY
10980     * @see #SCROLLBARS_INSIDE_INSET
10981     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10982     * @see #SCROLLBARS_OUTSIDE_INSET
10983     *
10984     * @attr ref android.R.styleable#View_scrollbarStyle
10985     */
10986    public void setScrollBarStyle(int style) {
10987        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10988            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10989            computeOpaqueFlags();
10990            resolvePadding();
10991        }
10992    }
10993
10994    /**
10995     * <p>Returns the current scrollbar style.</p>
10996     * @return the current scrollbar style
10997     * @see #SCROLLBARS_INSIDE_OVERLAY
10998     * @see #SCROLLBARS_INSIDE_INSET
10999     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11000     * @see #SCROLLBARS_OUTSIDE_INSET
11001     *
11002     * @attr ref android.R.styleable#View_scrollbarStyle
11003     */
11004    @ViewDebug.ExportedProperty(mapping = {
11005            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11006            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11007            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11008            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11009    })
11010    public int getScrollBarStyle() {
11011        return mViewFlags & SCROLLBARS_STYLE_MASK;
11012    }
11013
11014    /**
11015     * <p>Compute the horizontal range that the horizontal scrollbar
11016     * represents.</p>
11017     *
11018     * <p>The range is expressed in arbitrary units that must be the same as the
11019     * units used by {@link #computeHorizontalScrollExtent()} and
11020     * {@link #computeHorizontalScrollOffset()}.</p>
11021     *
11022     * <p>The default range is the drawing width of this view.</p>
11023     *
11024     * @return the total horizontal range represented by the horizontal
11025     *         scrollbar
11026     *
11027     * @see #computeHorizontalScrollExtent()
11028     * @see #computeHorizontalScrollOffset()
11029     * @see android.widget.ScrollBarDrawable
11030     */
11031    protected int computeHorizontalScrollRange() {
11032        return getWidth();
11033    }
11034
11035    /**
11036     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11037     * within the horizontal range. This value is used to compute the position
11038     * of the thumb within the scrollbar's track.</p>
11039     *
11040     * <p>The range is expressed in arbitrary units that must be the same as the
11041     * units used by {@link #computeHorizontalScrollRange()} and
11042     * {@link #computeHorizontalScrollExtent()}.</p>
11043     *
11044     * <p>The default offset is the scroll offset of this view.</p>
11045     *
11046     * @return the horizontal offset of the scrollbar's thumb
11047     *
11048     * @see #computeHorizontalScrollRange()
11049     * @see #computeHorizontalScrollExtent()
11050     * @see android.widget.ScrollBarDrawable
11051     */
11052    protected int computeHorizontalScrollOffset() {
11053        return mScrollX;
11054    }
11055
11056    /**
11057     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11058     * within the horizontal range. This value is used to compute the length
11059     * of the thumb within the scrollbar's track.</p>
11060     *
11061     * <p>The range is expressed in arbitrary units that must be the same as the
11062     * units used by {@link #computeHorizontalScrollRange()} and
11063     * {@link #computeHorizontalScrollOffset()}.</p>
11064     *
11065     * <p>The default extent is the drawing width of this view.</p>
11066     *
11067     * @return the horizontal extent of the scrollbar's thumb
11068     *
11069     * @see #computeHorizontalScrollRange()
11070     * @see #computeHorizontalScrollOffset()
11071     * @see android.widget.ScrollBarDrawable
11072     */
11073    protected int computeHorizontalScrollExtent() {
11074        return getWidth();
11075    }
11076
11077    /**
11078     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11079     *
11080     * <p>The range is expressed in arbitrary units that must be the same as the
11081     * units used by {@link #computeVerticalScrollExtent()} and
11082     * {@link #computeVerticalScrollOffset()}.</p>
11083     *
11084     * @return the total vertical range represented by the vertical scrollbar
11085     *
11086     * <p>The default range is the drawing height of this view.</p>
11087     *
11088     * @see #computeVerticalScrollExtent()
11089     * @see #computeVerticalScrollOffset()
11090     * @see android.widget.ScrollBarDrawable
11091     */
11092    protected int computeVerticalScrollRange() {
11093        return getHeight();
11094    }
11095
11096    /**
11097     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11098     * within the horizontal range. This value is used to compute the position
11099     * of the thumb within the scrollbar's track.</p>
11100     *
11101     * <p>The range is expressed in arbitrary units that must be the same as the
11102     * units used by {@link #computeVerticalScrollRange()} and
11103     * {@link #computeVerticalScrollExtent()}.</p>
11104     *
11105     * <p>The default offset is the scroll offset of this view.</p>
11106     *
11107     * @return the vertical offset of the scrollbar's thumb
11108     *
11109     * @see #computeVerticalScrollRange()
11110     * @see #computeVerticalScrollExtent()
11111     * @see android.widget.ScrollBarDrawable
11112     */
11113    protected int computeVerticalScrollOffset() {
11114        return mScrollY;
11115    }
11116
11117    /**
11118     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11119     * within the vertical range. This value is used to compute the length
11120     * of the thumb within the scrollbar's track.</p>
11121     *
11122     * <p>The range is expressed in arbitrary units that must be the same as the
11123     * units used by {@link #computeVerticalScrollRange()} and
11124     * {@link #computeVerticalScrollOffset()}.</p>
11125     *
11126     * <p>The default extent is the drawing height of this view.</p>
11127     *
11128     * @return the vertical extent of the scrollbar's thumb
11129     *
11130     * @see #computeVerticalScrollRange()
11131     * @see #computeVerticalScrollOffset()
11132     * @see android.widget.ScrollBarDrawable
11133     */
11134    protected int computeVerticalScrollExtent() {
11135        return getHeight();
11136    }
11137
11138    /**
11139     * Check if this view can be scrolled horizontally in a certain direction.
11140     *
11141     * @param direction Negative to check scrolling left, positive to check scrolling right.
11142     * @return true if this view can be scrolled in the specified direction, false otherwise.
11143     */
11144    public boolean canScrollHorizontally(int direction) {
11145        final int offset = computeHorizontalScrollOffset();
11146        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11147        if (range == 0) return false;
11148        if (direction < 0) {
11149            return offset > 0;
11150        } else {
11151            return offset < range - 1;
11152        }
11153    }
11154
11155    /**
11156     * Check if this view can be scrolled vertically in a certain direction.
11157     *
11158     * @param direction Negative to check scrolling up, positive to check scrolling down.
11159     * @return true if this view can be scrolled in the specified direction, false otherwise.
11160     */
11161    public boolean canScrollVertically(int direction) {
11162        final int offset = computeVerticalScrollOffset();
11163        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11164        if (range == 0) return false;
11165        if (direction < 0) {
11166            return offset > 0;
11167        } else {
11168            return offset < range - 1;
11169        }
11170    }
11171
11172    /**
11173     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11174     * scrollbars are painted only if they have been awakened first.</p>
11175     *
11176     * @param canvas the canvas on which to draw the scrollbars
11177     *
11178     * @see #awakenScrollBars(int)
11179     */
11180    protected final void onDrawScrollBars(Canvas canvas) {
11181        // scrollbars are drawn only when the animation is running
11182        final ScrollabilityCache cache = mScrollCache;
11183        if (cache != null) {
11184
11185            int state = cache.state;
11186
11187            if (state == ScrollabilityCache.OFF) {
11188                return;
11189            }
11190
11191            boolean invalidate = false;
11192
11193            if (state == ScrollabilityCache.FADING) {
11194                // We're fading -- get our fade interpolation
11195                if (cache.interpolatorValues == null) {
11196                    cache.interpolatorValues = new float[1];
11197                }
11198
11199                float[] values = cache.interpolatorValues;
11200
11201                // Stops the animation if we're done
11202                if (cache.scrollBarInterpolator.timeToValues(values) ==
11203                        Interpolator.Result.FREEZE_END) {
11204                    cache.state = ScrollabilityCache.OFF;
11205                } else {
11206                    cache.scrollBar.setAlpha(Math.round(values[0]));
11207                }
11208
11209                // This will make the scroll bars inval themselves after
11210                // drawing. We only want this when we're fading so that
11211                // we prevent excessive redraws
11212                invalidate = true;
11213            } else {
11214                // We're just on -- but we may have been fading before so
11215                // reset alpha
11216                cache.scrollBar.setAlpha(255);
11217            }
11218
11219
11220            final int viewFlags = mViewFlags;
11221
11222            final boolean drawHorizontalScrollBar =
11223                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11224            final boolean drawVerticalScrollBar =
11225                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11226                && !isVerticalScrollBarHidden();
11227
11228            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11229                final int width = mRight - mLeft;
11230                final int height = mBottom - mTop;
11231
11232                final ScrollBarDrawable scrollBar = cache.scrollBar;
11233
11234                final int scrollX = mScrollX;
11235                final int scrollY = mScrollY;
11236                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11237
11238                int left, top, right, bottom;
11239
11240                if (drawHorizontalScrollBar) {
11241                    int size = scrollBar.getSize(false);
11242                    if (size <= 0) {
11243                        size = cache.scrollBarSize;
11244                    }
11245
11246                    scrollBar.setParameters(computeHorizontalScrollRange(),
11247                                            computeHorizontalScrollOffset(),
11248                                            computeHorizontalScrollExtent(), false);
11249                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11250                            getVerticalScrollbarWidth() : 0;
11251                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11252                    left = scrollX + (mPaddingLeft & inside);
11253                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11254                    bottom = top + size;
11255                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11256                    if (invalidate) {
11257                        invalidate(left, top, right, bottom);
11258                    }
11259                }
11260
11261                if (drawVerticalScrollBar) {
11262                    int size = scrollBar.getSize(true);
11263                    if (size <= 0) {
11264                        size = cache.scrollBarSize;
11265                    }
11266
11267                    scrollBar.setParameters(computeVerticalScrollRange(),
11268                                            computeVerticalScrollOffset(),
11269                                            computeVerticalScrollExtent(), true);
11270                    switch (mVerticalScrollbarPosition) {
11271                        default:
11272                        case SCROLLBAR_POSITION_DEFAULT:
11273                        case SCROLLBAR_POSITION_RIGHT:
11274                            left = scrollX + width - size - (mUserPaddingRight & inside);
11275                            break;
11276                        case SCROLLBAR_POSITION_LEFT:
11277                            left = scrollX + (mUserPaddingLeft & inside);
11278                            break;
11279                    }
11280                    top = scrollY + (mPaddingTop & inside);
11281                    right = left + size;
11282                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11283                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11284                    if (invalidate) {
11285                        invalidate(left, top, right, bottom);
11286                    }
11287                }
11288            }
11289        }
11290    }
11291
11292    /**
11293     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11294     * FastScroller is visible.
11295     * @return whether to temporarily hide the vertical scrollbar
11296     * @hide
11297     */
11298    protected boolean isVerticalScrollBarHidden() {
11299        return false;
11300    }
11301
11302    /**
11303     * <p>Draw the horizontal scrollbar if
11304     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11305     *
11306     * @param canvas the canvas on which to draw the scrollbar
11307     * @param scrollBar the scrollbar's drawable
11308     *
11309     * @see #isHorizontalScrollBarEnabled()
11310     * @see #computeHorizontalScrollRange()
11311     * @see #computeHorizontalScrollExtent()
11312     * @see #computeHorizontalScrollOffset()
11313     * @see android.widget.ScrollBarDrawable
11314     * @hide
11315     */
11316    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11317            int l, int t, int r, int b) {
11318        scrollBar.setBounds(l, t, r, b);
11319        scrollBar.draw(canvas);
11320    }
11321
11322    /**
11323     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11324     * returns true.</p>
11325     *
11326     * @param canvas the canvas on which to draw the scrollbar
11327     * @param scrollBar the scrollbar's drawable
11328     *
11329     * @see #isVerticalScrollBarEnabled()
11330     * @see #computeVerticalScrollRange()
11331     * @see #computeVerticalScrollExtent()
11332     * @see #computeVerticalScrollOffset()
11333     * @see android.widget.ScrollBarDrawable
11334     * @hide
11335     */
11336    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11337            int l, int t, int r, int b) {
11338        scrollBar.setBounds(l, t, r, b);
11339        scrollBar.draw(canvas);
11340    }
11341
11342    /**
11343     * Implement this to do your drawing.
11344     *
11345     * @param canvas the canvas on which the background will be drawn
11346     */
11347    protected void onDraw(Canvas canvas) {
11348    }
11349
11350    /*
11351     * Caller is responsible for calling requestLayout if necessary.
11352     * (This allows addViewInLayout to not request a new layout.)
11353     */
11354    void assignParent(ViewParent parent) {
11355        if (mParent == null) {
11356            mParent = parent;
11357        } else if (parent == null) {
11358            mParent = null;
11359        } else {
11360            throw new RuntimeException("view " + this + " being added, but"
11361                    + " it already has a parent");
11362        }
11363    }
11364
11365    /**
11366     * This is called when the view is attached to a window.  At this point it
11367     * has a Surface and will start drawing.  Note that this function is
11368     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11369     * however it may be called any time before the first onDraw -- including
11370     * before or after {@link #onMeasure(int, int)}.
11371     *
11372     * @see #onDetachedFromWindow()
11373     */
11374    protected void onAttachedToWindow() {
11375        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11376            mParent.requestTransparentRegion(this);
11377        }
11378
11379        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11380            initialAwakenScrollBars();
11381            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11382        }
11383
11384        jumpDrawablesToCurrentState();
11385
11386        // Order is important here: LayoutDirection MUST be resolved before Padding
11387        // and TextDirection
11388        resolveLayoutDirection();
11389        resolvePadding();
11390        resolveTextDirection();
11391        resolveTextAlignment();
11392
11393        clearAccessibilityFocus();
11394        if (isFocused()) {
11395            InputMethodManager imm = InputMethodManager.peekInstance();
11396            imm.focusIn(this);
11397        }
11398
11399        if (mAttachInfo != null && mDisplayList != null) {
11400            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11401        }
11402    }
11403
11404    /**
11405     * @see #onScreenStateChanged(int)
11406     */
11407    void dispatchScreenStateChanged(int screenState) {
11408        onScreenStateChanged(screenState);
11409    }
11410
11411    /**
11412     * This method is called whenever the state of the screen this view is
11413     * attached to changes. A state change will usually occurs when the screen
11414     * turns on or off (whether it happens automatically or the user does it
11415     * manually.)
11416     *
11417     * @param screenState The new state of the screen. Can be either
11418     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11419     */
11420    public void onScreenStateChanged(int screenState) {
11421    }
11422
11423    /**
11424     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11425     */
11426    private boolean hasRtlSupport() {
11427        return mContext.getApplicationInfo().hasRtlSupport();
11428    }
11429
11430    /**
11431     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11432     * that the parent directionality can and will be resolved before its children.
11433     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11434     * @hide
11435     */
11436    public void resolveLayoutDirection() {
11437        // Clear any previous layout direction resolution
11438        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11439
11440        if (hasRtlSupport()) {
11441            // Set resolved depending on layout direction
11442            switch (getLayoutDirection()) {
11443                case LAYOUT_DIRECTION_INHERIT:
11444                    // If this is root view, no need to look at parent's layout dir.
11445                    if (canResolveLayoutDirection()) {
11446                        ViewGroup viewGroup = ((ViewGroup) mParent);
11447
11448                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11449                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11450                        }
11451                    } else {
11452                        // Nothing to do, LTR by default
11453                    }
11454                    break;
11455                case LAYOUT_DIRECTION_RTL:
11456                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11457                    break;
11458                case LAYOUT_DIRECTION_LOCALE:
11459                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11460                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11461                    }
11462                    break;
11463                default:
11464                    // Nothing to do, LTR by default
11465            }
11466        }
11467
11468        // Set to resolved
11469        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11470        onResolvedLayoutDirectionChanged();
11471        // Resolve padding
11472        resolvePadding();
11473    }
11474
11475    /**
11476     * Called when layout direction has been resolved.
11477     *
11478     * The default implementation does nothing.
11479     * @hide
11480     */
11481    public void onResolvedLayoutDirectionChanged() {
11482    }
11483
11484    /**
11485     * Resolve padding depending on layout direction.
11486     * @hide
11487     */
11488    public void resolvePadding() {
11489        // If the user specified the absolute padding (either with android:padding or
11490        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11491        // use the default padding or the padding from the background drawable
11492        // (stored at this point in mPadding*)
11493        int resolvedLayoutDirection = getResolvedLayoutDirection();
11494        switch (resolvedLayoutDirection) {
11495            case LAYOUT_DIRECTION_RTL:
11496                // Start user padding override Right user padding. Otherwise, if Right user
11497                // padding is not defined, use the default Right padding. If Right user padding
11498                // is defined, just use it.
11499                if (mUserPaddingStart >= 0) {
11500                    mUserPaddingRight = mUserPaddingStart;
11501                } else if (mUserPaddingRight < 0) {
11502                    mUserPaddingRight = mPaddingRight;
11503                }
11504                if (mUserPaddingEnd >= 0) {
11505                    mUserPaddingLeft = mUserPaddingEnd;
11506                } else if (mUserPaddingLeft < 0) {
11507                    mUserPaddingLeft = mPaddingLeft;
11508                }
11509                break;
11510            case LAYOUT_DIRECTION_LTR:
11511            default:
11512                // Start user padding override Left user padding. Otherwise, if Left user
11513                // padding is not defined, use the default left padding. If Left user padding
11514                // is defined, just use it.
11515                if (mUserPaddingStart >= 0) {
11516                    mUserPaddingLeft = mUserPaddingStart;
11517                } else if (mUserPaddingLeft < 0) {
11518                    mUserPaddingLeft = mPaddingLeft;
11519                }
11520                if (mUserPaddingEnd >= 0) {
11521                    mUserPaddingRight = mUserPaddingEnd;
11522                } else if (mUserPaddingRight < 0) {
11523                    mUserPaddingRight = mPaddingRight;
11524                }
11525        }
11526
11527        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11528
11529        if(isPaddingRelative()) {
11530            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11531        } else {
11532            recomputePadding();
11533        }
11534        onPaddingChanged(resolvedLayoutDirection);
11535    }
11536
11537    /**
11538     * Resolve padding depending on the layout direction. Subclasses that care about
11539     * padding resolution should override this method. The default implementation does
11540     * nothing.
11541     *
11542     * @param layoutDirection the direction of the layout
11543     *
11544     * @see {@link #LAYOUT_DIRECTION_LTR}
11545     * @see {@link #LAYOUT_DIRECTION_RTL}
11546     * @hide
11547     */
11548    public void onPaddingChanged(int layoutDirection) {
11549    }
11550
11551    /**
11552     * Check if layout direction resolution can be done.
11553     *
11554     * @return true if layout direction resolution can be done otherwise return false.
11555     * @hide
11556     */
11557    public boolean canResolveLayoutDirection() {
11558        switch (getLayoutDirection()) {
11559            case LAYOUT_DIRECTION_INHERIT:
11560                return (mParent != null) && (mParent instanceof ViewGroup);
11561            default:
11562                return true;
11563        }
11564    }
11565
11566    /**
11567     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11568     * when reset is done.
11569     * @hide
11570     */
11571    public void resetResolvedLayoutDirection() {
11572        // Reset the current resolved bits
11573        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11574        onResolvedLayoutDirectionReset();
11575        // Reset also the text direction
11576        resetResolvedTextDirection();
11577    }
11578
11579    /**
11580     * Called during reset of resolved layout direction.
11581     *
11582     * Subclasses need to override this method to clear cached information that depends on the
11583     * resolved layout direction, or to inform child views that inherit their layout direction.
11584     *
11585     * The default implementation does nothing.
11586     * @hide
11587     */
11588    public void onResolvedLayoutDirectionReset() {
11589    }
11590
11591    /**
11592     * Check if a Locale uses an RTL script.
11593     *
11594     * @param locale Locale to check
11595     * @return true if the Locale uses an RTL script.
11596     * @hide
11597     */
11598    protected static boolean isLayoutDirectionRtl(Locale locale) {
11599        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11600    }
11601
11602    /**
11603     * This is called when the view is detached from a window.  At this point it
11604     * no longer has a surface for drawing.
11605     *
11606     * @see #onAttachedToWindow()
11607     */
11608    protected void onDetachedFromWindow() {
11609        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11610
11611        removeUnsetPressCallback();
11612        removeLongPressCallback();
11613        removePerformClickCallback();
11614        removeSendViewScrolledAccessibilityEventCallback();
11615
11616        destroyDrawingCache();
11617
11618        destroyLayer(false);
11619
11620        if (mAttachInfo != null) {
11621            if (mDisplayList != null) {
11622                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11623            }
11624            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11625        } else {
11626            // Should never happen
11627            clearDisplayList();
11628        }
11629
11630        mCurrentAnimation = null;
11631
11632        resetResolvedLayoutDirection();
11633        resetResolvedTextAlignment();
11634        resetAccessibilityStateChanged();
11635    }
11636
11637    /**
11638     * @return The number of times this view has been attached to a window
11639     */
11640    protected int getWindowAttachCount() {
11641        return mWindowAttachCount;
11642    }
11643
11644    /**
11645     * Retrieve a unique token identifying the window this view is attached to.
11646     * @return Return the window's token for use in
11647     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11648     */
11649    public IBinder getWindowToken() {
11650        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11651    }
11652
11653    /**
11654     * Retrieve a unique token identifying the top-level "real" window of
11655     * the window that this view is attached to.  That is, this is like
11656     * {@link #getWindowToken}, except if the window this view in is a panel
11657     * window (attached to another containing window), then the token of
11658     * the containing window is returned instead.
11659     *
11660     * @return Returns the associated window token, either
11661     * {@link #getWindowToken()} or the containing window's token.
11662     */
11663    public IBinder getApplicationWindowToken() {
11664        AttachInfo ai = mAttachInfo;
11665        if (ai != null) {
11666            IBinder appWindowToken = ai.mPanelParentWindowToken;
11667            if (appWindowToken == null) {
11668                appWindowToken = ai.mWindowToken;
11669            }
11670            return appWindowToken;
11671        }
11672        return null;
11673    }
11674
11675    /**
11676     * Retrieve private session object this view hierarchy is using to
11677     * communicate with the window manager.
11678     * @return the session object to communicate with the window manager
11679     */
11680    /*package*/ IWindowSession getWindowSession() {
11681        return mAttachInfo != null ? mAttachInfo.mSession : null;
11682    }
11683
11684    /**
11685     * @param info the {@link android.view.View.AttachInfo} to associated with
11686     *        this view
11687     */
11688    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11689        //System.out.println("Attached! " + this);
11690        mAttachInfo = info;
11691        mWindowAttachCount++;
11692        // We will need to evaluate the drawable state at least once.
11693        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11694        if (mFloatingTreeObserver != null) {
11695            info.mTreeObserver.merge(mFloatingTreeObserver);
11696            mFloatingTreeObserver = null;
11697        }
11698        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11699            mAttachInfo.mScrollContainers.add(this);
11700            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11701        }
11702        performCollectViewAttributes(mAttachInfo, visibility);
11703        onAttachedToWindow();
11704
11705        ListenerInfo li = mListenerInfo;
11706        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11707                li != null ? li.mOnAttachStateChangeListeners : null;
11708        if (listeners != null && listeners.size() > 0) {
11709            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11710            // perform the dispatching. The iterator is a safe guard against listeners that
11711            // could mutate the list by calling the various add/remove methods. This prevents
11712            // the array from being modified while we iterate it.
11713            for (OnAttachStateChangeListener listener : listeners) {
11714                listener.onViewAttachedToWindow(this);
11715            }
11716        }
11717
11718        int vis = info.mWindowVisibility;
11719        if (vis != GONE) {
11720            onWindowVisibilityChanged(vis);
11721        }
11722        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11723            // If nobody has evaluated the drawable state yet, then do it now.
11724            refreshDrawableState();
11725        }
11726    }
11727
11728    void dispatchDetachedFromWindow() {
11729        AttachInfo info = mAttachInfo;
11730        if (info != null) {
11731            int vis = info.mWindowVisibility;
11732            if (vis != GONE) {
11733                onWindowVisibilityChanged(GONE);
11734            }
11735        }
11736
11737        onDetachedFromWindow();
11738
11739        ListenerInfo li = mListenerInfo;
11740        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11741                li != null ? li.mOnAttachStateChangeListeners : null;
11742        if (listeners != null && listeners.size() > 0) {
11743            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11744            // perform the dispatching. The iterator is a safe guard against listeners that
11745            // could mutate the list by calling the various add/remove methods. This prevents
11746            // the array from being modified while we iterate it.
11747            for (OnAttachStateChangeListener listener : listeners) {
11748                listener.onViewDetachedFromWindow(this);
11749            }
11750        }
11751
11752        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11753            mAttachInfo.mScrollContainers.remove(this);
11754            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11755        }
11756
11757        mAttachInfo = null;
11758    }
11759
11760    /**
11761     * Store this view hierarchy's frozen state into the given container.
11762     *
11763     * @param container The SparseArray in which to save the view's state.
11764     *
11765     * @see #restoreHierarchyState(android.util.SparseArray)
11766     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11767     * @see #onSaveInstanceState()
11768     */
11769    public void saveHierarchyState(SparseArray<Parcelable> container) {
11770        dispatchSaveInstanceState(container);
11771    }
11772
11773    /**
11774     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11775     * this view and its children. May be overridden to modify how freezing happens to a
11776     * view's children; for example, some views may want to not store state for their children.
11777     *
11778     * @param container The SparseArray in which to save the view's state.
11779     *
11780     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11781     * @see #saveHierarchyState(android.util.SparseArray)
11782     * @see #onSaveInstanceState()
11783     */
11784    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11785        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11786            mPrivateFlags &= ~SAVE_STATE_CALLED;
11787            Parcelable state = onSaveInstanceState();
11788            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11789                throw new IllegalStateException(
11790                        "Derived class did not call super.onSaveInstanceState()");
11791            }
11792            if (state != null) {
11793                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11794                // + ": " + state);
11795                container.put(mID, state);
11796            }
11797        }
11798    }
11799
11800    /**
11801     * Hook allowing a view to generate a representation of its internal state
11802     * that can later be used to create a new instance with that same state.
11803     * This state should only contain information that is not persistent or can
11804     * not be reconstructed later. For example, you will never store your
11805     * current position on screen because that will be computed again when a
11806     * new instance of the view is placed in its view hierarchy.
11807     * <p>
11808     * Some examples of things you may store here: the current cursor position
11809     * in a text view (but usually not the text itself since that is stored in a
11810     * content provider or other persistent storage), the currently selected
11811     * item in a list view.
11812     *
11813     * @return Returns a Parcelable object containing the view's current dynamic
11814     *         state, or null if there is nothing interesting to save. The
11815     *         default implementation returns null.
11816     * @see #onRestoreInstanceState(android.os.Parcelable)
11817     * @see #saveHierarchyState(android.util.SparseArray)
11818     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11819     * @see #setSaveEnabled(boolean)
11820     */
11821    protected Parcelable onSaveInstanceState() {
11822        mPrivateFlags |= SAVE_STATE_CALLED;
11823        return BaseSavedState.EMPTY_STATE;
11824    }
11825
11826    /**
11827     * Restore this view hierarchy's frozen state from the given container.
11828     *
11829     * @param container The SparseArray which holds previously frozen states.
11830     *
11831     * @see #saveHierarchyState(android.util.SparseArray)
11832     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11833     * @see #onRestoreInstanceState(android.os.Parcelable)
11834     */
11835    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11836        dispatchRestoreInstanceState(container);
11837    }
11838
11839    /**
11840     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11841     * state for this view and its children. May be overridden to modify how restoring
11842     * happens to a view's children; for example, some views may want to not store state
11843     * for their children.
11844     *
11845     * @param container The SparseArray which holds previously saved state.
11846     *
11847     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11848     * @see #restoreHierarchyState(android.util.SparseArray)
11849     * @see #onRestoreInstanceState(android.os.Parcelable)
11850     */
11851    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11852        if (mID != NO_ID) {
11853            Parcelable state = container.get(mID);
11854            if (state != null) {
11855                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11856                // + ": " + state);
11857                mPrivateFlags &= ~SAVE_STATE_CALLED;
11858                onRestoreInstanceState(state);
11859                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11860                    throw new IllegalStateException(
11861                            "Derived class did not call super.onRestoreInstanceState()");
11862                }
11863            }
11864        }
11865    }
11866
11867    /**
11868     * Hook allowing a view to re-apply a representation of its internal state that had previously
11869     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11870     * null state.
11871     *
11872     * @param state The frozen state that had previously been returned by
11873     *        {@link #onSaveInstanceState}.
11874     *
11875     * @see #onSaveInstanceState()
11876     * @see #restoreHierarchyState(android.util.SparseArray)
11877     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11878     */
11879    protected void onRestoreInstanceState(Parcelable state) {
11880        mPrivateFlags |= SAVE_STATE_CALLED;
11881        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11882            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11883                    + "received " + state.getClass().toString() + " instead. This usually happens "
11884                    + "when two views of different type have the same id in the same hierarchy. "
11885                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11886                    + "other views do not use the same id.");
11887        }
11888    }
11889
11890    /**
11891     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11892     *
11893     * @return the drawing start time in milliseconds
11894     */
11895    public long getDrawingTime() {
11896        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11897    }
11898
11899    /**
11900     * <p>Enables or disables the duplication of the parent's state into this view. When
11901     * duplication is enabled, this view gets its drawable state from its parent rather
11902     * than from its own internal properties.</p>
11903     *
11904     * <p>Note: in the current implementation, setting this property to true after the
11905     * view was added to a ViewGroup might have no effect at all. This property should
11906     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11907     *
11908     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11909     * property is enabled, an exception will be thrown.</p>
11910     *
11911     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11912     * parent, these states should not be affected by this method.</p>
11913     *
11914     * @param enabled True to enable duplication of the parent's drawable state, false
11915     *                to disable it.
11916     *
11917     * @see #getDrawableState()
11918     * @see #isDuplicateParentStateEnabled()
11919     */
11920    public void setDuplicateParentStateEnabled(boolean enabled) {
11921        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11922    }
11923
11924    /**
11925     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11926     *
11927     * @return True if this view's drawable state is duplicated from the parent,
11928     *         false otherwise
11929     *
11930     * @see #getDrawableState()
11931     * @see #setDuplicateParentStateEnabled(boolean)
11932     */
11933    public boolean isDuplicateParentStateEnabled() {
11934        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11935    }
11936
11937    /**
11938     * <p>Specifies the type of layer backing this view. The layer can be
11939     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11940     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11941     *
11942     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11943     * instance that controls how the layer is composed on screen. The following
11944     * properties of the paint are taken into account when composing the layer:</p>
11945     * <ul>
11946     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11947     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11948     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11949     * </ul>
11950     *
11951     * <p>If this view has an alpha value set to < 1.0 by calling
11952     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11953     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11954     * equivalent to setting a hardware layer on this view and providing a paint with
11955     * the desired alpha value.<p>
11956     *
11957     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11958     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11959     * for more information on when and how to use layers.</p>
11960     *
11961     * @param layerType The ype of layer to use with this view, must be one of
11962     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11963     *        {@link #LAYER_TYPE_HARDWARE}
11964     * @param paint The paint used to compose the layer. This argument is optional
11965     *        and can be null. It is ignored when the layer type is
11966     *        {@link #LAYER_TYPE_NONE}
11967     *
11968     * @see #getLayerType()
11969     * @see #LAYER_TYPE_NONE
11970     * @see #LAYER_TYPE_SOFTWARE
11971     * @see #LAYER_TYPE_HARDWARE
11972     * @see #setAlpha(float)
11973     *
11974     * @attr ref android.R.styleable#View_layerType
11975     */
11976    public void setLayerType(int layerType, Paint paint) {
11977        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11978            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11979                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11980        }
11981
11982        if (layerType == mLayerType) {
11983            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11984                mLayerPaint = paint == null ? new Paint() : paint;
11985                invalidateParentCaches();
11986                invalidate(true);
11987            }
11988            return;
11989        }
11990
11991        // Destroy any previous software drawing cache if needed
11992        switch (mLayerType) {
11993            case LAYER_TYPE_HARDWARE:
11994                destroyLayer(false);
11995                // fall through - non-accelerated views may use software layer mechanism instead
11996            case LAYER_TYPE_SOFTWARE:
11997                destroyDrawingCache();
11998                break;
11999            default:
12000                break;
12001        }
12002
12003        mLayerType = layerType;
12004        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12005        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12006        mLocalDirtyRect = layerDisabled ? null : new Rect();
12007
12008        invalidateParentCaches();
12009        invalidate(true);
12010    }
12011
12012    /**
12013     * Indicates whether this view has a static layer. A view with layer type
12014     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12015     * dynamic.
12016     */
12017    boolean hasStaticLayer() {
12018        return true;
12019    }
12020
12021    /**
12022     * Indicates what type of layer is currently associated with this view. By default
12023     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12024     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12025     * for more information on the different types of layers.
12026     *
12027     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12028     *         {@link #LAYER_TYPE_HARDWARE}
12029     *
12030     * @see #setLayerType(int, android.graphics.Paint)
12031     * @see #buildLayer()
12032     * @see #LAYER_TYPE_NONE
12033     * @see #LAYER_TYPE_SOFTWARE
12034     * @see #LAYER_TYPE_HARDWARE
12035     */
12036    public int getLayerType() {
12037        return mLayerType;
12038    }
12039
12040    /**
12041     * Forces this view's layer to be created and this view to be rendered
12042     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12043     * invoking this method will have no effect.
12044     *
12045     * This method can for instance be used to render a view into its layer before
12046     * starting an animation. If this view is complex, rendering into the layer
12047     * before starting the animation will avoid skipping frames.
12048     *
12049     * @throws IllegalStateException If this view is not attached to a window
12050     *
12051     * @see #setLayerType(int, android.graphics.Paint)
12052     */
12053    public void buildLayer() {
12054        if (mLayerType == LAYER_TYPE_NONE) return;
12055
12056        if (mAttachInfo == null) {
12057            throw new IllegalStateException("This view must be attached to a window first");
12058        }
12059
12060        switch (mLayerType) {
12061            case LAYER_TYPE_HARDWARE:
12062                if (mAttachInfo.mHardwareRenderer != null &&
12063                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12064                        mAttachInfo.mHardwareRenderer.validate()) {
12065                    getHardwareLayer();
12066                }
12067                break;
12068            case LAYER_TYPE_SOFTWARE:
12069                buildDrawingCache(true);
12070                break;
12071        }
12072    }
12073
12074    // Make sure the HardwareRenderer.validate() was invoked before calling this method
12075    void flushLayer() {
12076        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
12077            mHardwareLayer.flush();
12078        }
12079    }
12080
12081    /**
12082     * <p>Returns a hardware layer that can be used to draw this view again
12083     * without executing its draw method.</p>
12084     *
12085     * @return A HardwareLayer ready to render, or null if an error occurred.
12086     */
12087    HardwareLayer getHardwareLayer() {
12088        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12089                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12090            return null;
12091        }
12092
12093        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12094
12095        final int width = mRight - mLeft;
12096        final int height = mBottom - mTop;
12097
12098        if (width == 0 || height == 0) {
12099            return null;
12100        }
12101
12102        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12103            if (mHardwareLayer == null) {
12104                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12105                        width, height, isOpaque());
12106                mLocalDirtyRect.set(0, 0, width, height);
12107            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12108                mHardwareLayer.resize(width, height);
12109                mLocalDirtyRect.set(0, 0, width, height);
12110            }
12111
12112            // The layer is not valid if the underlying GPU resources cannot be allocated
12113            if (!mHardwareLayer.isValid()) {
12114                return null;
12115            }
12116
12117            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12118            mLocalDirtyRect.setEmpty();
12119        }
12120
12121        return mHardwareLayer;
12122    }
12123
12124    /**
12125     * Destroys this View's hardware layer if possible.
12126     *
12127     * @return True if the layer was destroyed, false otherwise.
12128     *
12129     * @see #setLayerType(int, android.graphics.Paint)
12130     * @see #LAYER_TYPE_HARDWARE
12131     */
12132    boolean destroyLayer(boolean valid) {
12133        if (mHardwareLayer != null) {
12134            AttachInfo info = mAttachInfo;
12135            if (info != null && info.mHardwareRenderer != null &&
12136                    info.mHardwareRenderer.isEnabled() &&
12137                    (valid || info.mHardwareRenderer.validate())) {
12138                mHardwareLayer.destroy();
12139                mHardwareLayer = null;
12140
12141                invalidate(true);
12142                invalidateParentCaches();
12143            }
12144            return true;
12145        }
12146        return false;
12147    }
12148
12149    /**
12150     * Destroys all hardware rendering resources. This method is invoked
12151     * when the system needs to reclaim resources. Upon execution of this
12152     * method, you should free any OpenGL resources created by the view.
12153     *
12154     * Note: you <strong>must</strong> call
12155     * <code>super.destroyHardwareResources()</code> when overriding
12156     * this method.
12157     *
12158     * @hide
12159     */
12160    protected void destroyHardwareResources() {
12161        destroyLayer(true);
12162    }
12163
12164    /**
12165     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12166     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12167     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12168     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12169     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12170     * null.</p>
12171     *
12172     * <p>Enabling the drawing cache is similar to
12173     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12174     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12175     * drawing cache has no effect on rendering because the system uses a different mechanism
12176     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12177     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12178     * for information on how to enable software and hardware layers.</p>
12179     *
12180     * <p>This API can be used to manually generate
12181     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12182     * {@link #getDrawingCache()}.</p>
12183     *
12184     * @param enabled true to enable the drawing cache, false otherwise
12185     *
12186     * @see #isDrawingCacheEnabled()
12187     * @see #getDrawingCache()
12188     * @see #buildDrawingCache()
12189     * @see #setLayerType(int, android.graphics.Paint)
12190     */
12191    public void setDrawingCacheEnabled(boolean enabled) {
12192        mCachingFailed = false;
12193        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12194    }
12195
12196    /**
12197     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12198     *
12199     * @return true if the drawing cache is enabled
12200     *
12201     * @see #setDrawingCacheEnabled(boolean)
12202     * @see #getDrawingCache()
12203     */
12204    @ViewDebug.ExportedProperty(category = "drawing")
12205    public boolean isDrawingCacheEnabled() {
12206        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12207    }
12208
12209    /**
12210     * Debugging utility which recursively outputs the dirty state of a view and its
12211     * descendants.
12212     *
12213     * @hide
12214     */
12215    @SuppressWarnings({"UnusedDeclaration"})
12216    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12217        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12218                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12219                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12220                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12221        if (clear) {
12222            mPrivateFlags &= clearMask;
12223        }
12224        if (this instanceof ViewGroup) {
12225            ViewGroup parent = (ViewGroup) this;
12226            final int count = parent.getChildCount();
12227            for (int i = 0; i < count; i++) {
12228                final View child = parent.getChildAt(i);
12229                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12230            }
12231        }
12232    }
12233
12234    /**
12235     * This method is used by ViewGroup to cause its children to restore or recreate their
12236     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12237     * to recreate its own display list, which would happen if it went through the normal
12238     * draw/dispatchDraw mechanisms.
12239     *
12240     * @hide
12241     */
12242    protected void dispatchGetDisplayList() {}
12243
12244    /**
12245     * A view that is not attached or hardware accelerated cannot create a display list.
12246     * This method checks these conditions and returns the appropriate result.
12247     *
12248     * @return true if view has the ability to create a display list, false otherwise.
12249     *
12250     * @hide
12251     */
12252    public boolean canHaveDisplayList() {
12253        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12254    }
12255
12256    /**
12257     * @return The HardwareRenderer associated with that view or null if hardware rendering
12258     * is not supported or this this has not been attached to a window.
12259     *
12260     * @hide
12261     */
12262    public HardwareRenderer getHardwareRenderer() {
12263        if (mAttachInfo != null) {
12264            return mAttachInfo.mHardwareRenderer;
12265        }
12266        return null;
12267    }
12268
12269    /**
12270     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12271     * Otherwise, the same display list will be returned (after having been rendered into
12272     * along the way, depending on the invalidation state of the view).
12273     *
12274     * @param displayList The previous version of this displayList, could be null.
12275     * @param isLayer Whether the requester of the display list is a layer. If so,
12276     * the view will avoid creating a layer inside the resulting display list.
12277     * @return A new or reused DisplayList object.
12278     */
12279    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12280        if (!canHaveDisplayList()) {
12281            return null;
12282        }
12283
12284        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12285                displayList == null || !displayList.isValid() ||
12286                (!isLayer && mRecreateDisplayList))) {
12287            // Don't need to recreate the display list, just need to tell our
12288            // children to restore/recreate theirs
12289            if (displayList != null && displayList.isValid() &&
12290                    !isLayer && !mRecreateDisplayList) {
12291                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12292                mPrivateFlags &= ~DIRTY_MASK;
12293                dispatchGetDisplayList();
12294
12295                return displayList;
12296            }
12297
12298            if (!isLayer) {
12299                // If we got here, we're recreating it. Mark it as such to ensure that
12300                // we copy in child display lists into ours in drawChild()
12301                mRecreateDisplayList = true;
12302            }
12303            if (displayList == null) {
12304                final String name = getClass().getSimpleName();
12305                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12306                // If we're creating a new display list, make sure our parent gets invalidated
12307                // since they will need to recreate their display list to account for this
12308                // new child display list.
12309                invalidateParentCaches();
12310            }
12311
12312            boolean caching = false;
12313            final HardwareCanvas canvas = displayList.start();
12314            int width = mRight - mLeft;
12315            int height = mBottom - mTop;
12316
12317            try {
12318                canvas.setViewport(width, height);
12319                // The dirty rect should always be null for a display list
12320                canvas.onPreDraw(null);
12321                int layerType = (
12322                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12323                        getLayerType() : LAYER_TYPE_NONE;
12324                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12325                    if (layerType == LAYER_TYPE_HARDWARE) {
12326                        final HardwareLayer layer = getHardwareLayer();
12327                        if (layer != null && layer.isValid()) {
12328                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12329                        } else {
12330                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12331                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12332                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12333                        }
12334                        caching = true;
12335                    } else {
12336                        buildDrawingCache(true);
12337                        Bitmap cache = getDrawingCache(true);
12338                        if (cache != null) {
12339                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12340                            caching = true;
12341                        }
12342                    }
12343                } else {
12344
12345                    computeScroll();
12346
12347                    canvas.translate(-mScrollX, -mScrollY);
12348                    if (!isLayer) {
12349                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12350                        mPrivateFlags &= ~DIRTY_MASK;
12351                    }
12352
12353                    // Fast path for layouts with no backgrounds
12354                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12355                        dispatchDraw(canvas);
12356                    } else {
12357                        draw(canvas);
12358                    }
12359                }
12360            } finally {
12361                canvas.onPostDraw();
12362
12363                displayList.end();
12364                displayList.setCaching(caching);
12365                if (isLayer) {
12366                    displayList.setLeftTopRightBottom(0, 0, width, height);
12367                } else {
12368                    setDisplayListProperties(displayList);
12369                }
12370            }
12371        } else if (!isLayer) {
12372            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12373            mPrivateFlags &= ~DIRTY_MASK;
12374        }
12375
12376        return displayList;
12377    }
12378
12379    /**
12380     * Get the DisplayList for the HardwareLayer
12381     *
12382     * @param layer The HardwareLayer whose DisplayList we want
12383     * @return A DisplayList fopr the specified HardwareLayer
12384     */
12385    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12386        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12387        layer.setDisplayList(displayList);
12388        return displayList;
12389    }
12390
12391
12392    /**
12393     * <p>Returns a display list that can be used to draw this view again
12394     * without executing its draw method.</p>
12395     *
12396     * @return A DisplayList ready to replay, or null if caching is not enabled.
12397     *
12398     * @hide
12399     */
12400    public DisplayList getDisplayList() {
12401        mDisplayList = getDisplayList(mDisplayList, false);
12402        return mDisplayList;
12403    }
12404
12405    private void clearDisplayList() {
12406        if (mDisplayList != null) {
12407            mDisplayList.invalidate();
12408            mDisplayList.clear();
12409        }
12410    }
12411
12412    /**
12413     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12414     *
12415     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12416     *
12417     * @see #getDrawingCache(boolean)
12418     */
12419    public Bitmap getDrawingCache() {
12420        return getDrawingCache(false);
12421    }
12422
12423    /**
12424     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12425     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12426     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12427     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12428     * request the drawing cache by calling this method and draw it on screen if the
12429     * returned bitmap is not null.</p>
12430     *
12431     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12432     * this method will create a bitmap of the same size as this view. Because this bitmap
12433     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12434     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12435     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12436     * size than the view. This implies that your application must be able to handle this
12437     * size.</p>
12438     *
12439     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12440     *        the current density of the screen when the application is in compatibility
12441     *        mode.
12442     *
12443     * @return A bitmap representing this view or null if cache is disabled.
12444     *
12445     * @see #setDrawingCacheEnabled(boolean)
12446     * @see #isDrawingCacheEnabled()
12447     * @see #buildDrawingCache(boolean)
12448     * @see #destroyDrawingCache()
12449     */
12450    public Bitmap getDrawingCache(boolean autoScale) {
12451        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12452            return null;
12453        }
12454        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12455            buildDrawingCache(autoScale);
12456        }
12457        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12458    }
12459
12460    /**
12461     * <p>Frees the resources used by the drawing cache. If you call
12462     * {@link #buildDrawingCache()} manually without calling
12463     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12464     * should cleanup the cache with this method afterwards.</p>
12465     *
12466     * @see #setDrawingCacheEnabled(boolean)
12467     * @see #buildDrawingCache()
12468     * @see #getDrawingCache()
12469     */
12470    public void destroyDrawingCache() {
12471        if (mDrawingCache != null) {
12472            mDrawingCache.recycle();
12473            mDrawingCache = null;
12474        }
12475        if (mUnscaledDrawingCache != null) {
12476            mUnscaledDrawingCache.recycle();
12477            mUnscaledDrawingCache = null;
12478        }
12479    }
12480
12481    /**
12482     * Setting a solid background color for the drawing cache's bitmaps will improve
12483     * performance and memory usage. Note, though that this should only be used if this
12484     * view will always be drawn on top of a solid color.
12485     *
12486     * @param color The background color to use for the drawing cache's bitmap
12487     *
12488     * @see #setDrawingCacheEnabled(boolean)
12489     * @see #buildDrawingCache()
12490     * @see #getDrawingCache()
12491     */
12492    public void setDrawingCacheBackgroundColor(int color) {
12493        if (color != mDrawingCacheBackgroundColor) {
12494            mDrawingCacheBackgroundColor = color;
12495            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12496        }
12497    }
12498
12499    /**
12500     * @see #setDrawingCacheBackgroundColor(int)
12501     *
12502     * @return The background color to used for the drawing cache's bitmap
12503     */
12504    public int getDrawingCacheBackgroundColor() {
12505        return mDrawingCacheBackgroundColor;
12506    }
12507
12508    /**
12509     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12510     *
12511     * @see #buildDrawingCache(boolean)
12512     */
12513    public void buildDrawingCache() {
12514        buildDrawingCache(false);
12515    }
12516
12517    /**
12518     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12519     *
12520     * <p>If you call {@link #buildDrawingCache()} manually without calling
12521     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12522     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12523     *
12524     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12525     * this method will create a bitmap of the same size as this view. Because this bitmap
12526     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12527     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12528     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12529     * size than the view. This implies that your application must be able to handle this
12530     * size.</p>
12531     *
12532     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12533     * you do not need the drawing cache bitmap, calling this method will increase memory
12534     * usage and cause the view to be rendered in software once, thus negatively impacting
12535     * performance.</p>
12536     *
12537     * @see #getDrawingCache()
12538     * @see #destroyDrawingCache()
12539     */
12540    public void buildDrawingCache(boolean autoScale) {
12541        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12542                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12543            mCachingFailed = false;
12544
12545            int width = mRight - mLeft;
12546            int height = mBottom - mTop;
12547
12548            final AttachInfo attachInfo = mAttachInfo;
12549            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12550
12551            if (autoScale && scalingRequired) {
12552                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12553                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12554            }
12555
12556            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12557            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12558            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12559
12560            if (width <= 0 || height <= 0 ||
12561                     // Projected bitmap size in bytes
12562                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12563                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12564                destroyDrawingCache();
12565                mCachingFailed = true;
12566                return;
12567            }
12568
12569            boolean clear = true;
12570            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12571
12572            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12573                Bitmap.Config quality;
12574                if (!opaque) {
12575                    // Never pick ARGB_4444 because it looks awful
12576                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12577                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12578                        case DRAWING_CACHE_QUALITY_AUTO:
12579                            quality = Bitmap.Config.ARGB_8888;
12580                            break;
12581                        case DRAWING_CACHE_QUALITY_LOW:
12582                            quality = Bitmap.Config.ARGB_8888;
12583                            break;
12584                        case DRAWING_CACHE_QUALITY_HIGH:
12585                            quality = Bitmap.Config.ARGB_8888;
12586                            break;
12587                        default:
12588                            quality = Bitmap.Config.ARGB_8888;
12589                            break;
12590                    }
12591                } else {
12592                    // Optimization for translucent windows
12593                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12594                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12595                }
12596
12597                // Try to cleanup memory
12598                if (bitmap != null) bitmap.recycle();
12599
12600                try {
12601                    bitmap = Bitmap.createBitmap(width, height, quality);
12602                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12603                    if (autoScale) {
12604                        mDrawingCache = bitmap;
12605                    } else {
12606                        mUnscaledDrawingCache = bitmap;
12607                    }
12608                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12609                } catch (OutOfMemoryError e) {
12610                    // If there is not enough memory to create the bitmap cache, just
12611                    // ignore the issue as bitmap caches are not required to draw the
12612                    // view hierarchy
12613                    if (autoScale) {
12614                        mDrawingCache = null;
12615                    } else {
12616                        mUnscaledDrawingCache = null;
12617                    }
12618                    mCachingFailed = true;
12619                    return;
12620                }
12621
12622                clear = drawingCacheBackgroundColor != 0;
12623            }
12624
12625            Canvas canvas;
12626            if (attachInfo != null) {
12627                canvas = attachInfo.mCanvas;
12628                if (canvas == null) {
12629                    canvas = new Canvas();
12630                }
12631                canvas.setBitmap(bitmap);
12632                // Temporarily clobber the cached Canvas in case one of our children
12633                // is also using a drawing cache. Without this, the children would
12634                // steal the canvas by attaching their own bitmap to it and bad, bad
12635                // thing would happen (invisible views, corrupted drawings, etc.)
12636                attachInfo.mCanvas = null;
12637            } else {
12638                // This case should hopefully never or seldom happen
12639                canvas = new Canvas(bitmap);
12640            }
12641
12642            if (clear) {
12643                bitmap.eraseColor(drawingCacheBackgroundColor);
12644            }
12645
12646            computeScroll();
12647            final int restoreCount = canvas.save();
12648
12649            if (autoScale && scalingRequired) {
12650                final float scale = attachInfo.mApplicationScale;
12651                canvas.scale(scale, scale);
12652            }
12653
12654            canvas.translate(-mScrollX, -mScrollY);
12655
12656            mPrivateFlags |= DRAWN;
12657            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12658                    mLayerType != LAYER_TYPE_NONE) {
12659                mPrivateFlags |= DRAWING_CACHE_VALID;
12660            }
12661
12662            // Fast path for layouts with no backgrounds
12663            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12664                mPrivateFlags &= ~DIRTY_MASK;
12665                dispatchDraw(canvas);
12666            } else {
12667                draw(canvas);
12668            }
12669
12670            canvas.restoreToCount(restoreCount);
12671            canvas.setBitmap(null);
12672
12673            if (attachInfo != null) {
12674                // Restore the cached Canvas for our siblings
12675                attachInfo.mCanvas = canvas;
12676            }
12677        }
12678    }
12679
12680    /**
12681     * Create a snapshot of the view into a bitmap.  We should probably make
12682     * some form of this public, but should think about the API.
12683     */
12684    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12685        int width = mRight - mLeft;
12686        int height = mBottom - mTop;
12687
12688        final AttachInfo attachInfo = mAttachInfo;
12689        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12690        width = (int) ((width * scale) + 0.5f);
12691        height = (int) ((height * scale) + 0.5f);
12692
12693        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12694        if (bitmap == null) {
12695            throw new OutOfMemoryError();
12696        }
12697
12698        Resources resources = getResources();
12699        if (resources != null) {
12700            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12701        }
12702
12703        Canvas canvas;
12704        if (attachInfo != null) {
12705            canvas = attachInfo.mCanvas;
12706            if (canvas == null) {
12707                canvas = new Canvas();
12708            }
12709            canvas.setBitmap(bitmap);
12710            // Temporarily clobber the cached Canvas in case one of our children
12711            // is also using a drawing cache. Without this, the children would
12712            // steal the canvas by attaching their own bitmap to it and bad, bad
12713            // things would happen (invisible views, corrupted drawings, etc.)
12714            attachInfo.mCanvas = null;
12715        } else {
12716            // This case should hopefully never or seldom happen
12717            canvas = new Canvas(bitmap);
12718        }
12719
12720        if ((backgroundColor & 0xff000000) != 0) {
12721            bitmap.eraseColor(backgroundColor);
12722        }
12723
12724        computeScroll();
12725        final int restoreCount = canvas.save();
12726        canvas.scale(scale, scale);
12727        canvas.translate(-mScrollX, -mScrollY);
12728
12729        // Temporarily remove the dirty mask
12730        int flags = mPrivateFlags;
12731        mPrivateFlags &= ~DIRTY_MASK;
12732
12733        // Fast path for layouts with no backgrounds
12734        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12735            dispatchDraw(canvas);
12736        } else {
12737            draw(canvas);
12738        }
12739
12740        mPrivateFlags = flags;
12741
12742        canvas.restoreToCount(restoreCount);
12743        canvas.setBitmap(null);
12744
12745        if (attachInfo != null) {
12746            // Restore the cached Canvas for our siblings
12747            attachInfo.mCanvas = canvas;
12748        }
12749
12750        return bitmap;
12751    }
12752
12753    /**
12754     * Indicates whether this View is currently in edit mode. A View is usually
12755     * in edit mode when displayed within a developer tool. For instance, if
12756     * this View is being drawn by a visual user interface builder, this method
12757     * should return true.
12758     *
12759     * Subclasses should check the return value of this method to provide
12760     * different behaviors if their normal behavior might interfere with the
12761     * host environment. For instance: the class spawns a thread in its
12762     * constructor, the drawing code relies on device-specific features, etc.
12763     *
12764     * This method is usually checked in the drawing code of custom widgets.
12765     *
12766     * @return True if this View is in edit mode, false otherwise.
12767     */
12768    public boolean isInEditMode() {
12769        return false;
12770    }
12771
12772    /**
12773     * If the View draws content inside its padding and enables fading edges,
12774     * it needs to support padding offsets. Padding offsets are added to the
12775     * fading edges to extend the length of the fade so that it covers pixels
12776     * drawn inside the padding.
12777     *
12778     * Subclasses of this class should override this method if they need
12779     * to draw content inside the padding.
12780     *
12781     * @return True if padding offset must be applied, false otherwise.
12782     *
12783     * @see #getLeftPaddingOffset()
12784     * @see #getRightPaddingOffset()
12785     * @see #getTopPaddingOffset()
12786     * @see #getBottomPaddingOffset()
12787     *
12788     * @since CURRENT
12789     */
12790    protected boolean isPaddingOffsetRequired() {
12791        return false;
12792    }
12793
12794    /**
12795     * Amount by which to extend the left fading region. Called only when
12796     * {@link #isPaddingOffsetRequired()} returns true.
12797     *
12798     * @return The left padding offset in pixels.
12799     *
12800     * @see #isPaddingOffsetRequired()
12801     *
12802     * @since CURRENT
12803     */
12804    protected int getLeftPaddingOffset() {
12805        return 0;
12806    }
12807
12808    /**
12809     * Amount by which to extend the right fading region. Called only when
12810     * {@link #isPaddingOffsetRequired()} returns true.
12811     *
12812     * @return The right padding offset in pixels.
12813     *
12814     * @see #isPaddingOffsetRequired()
12815     *
12816     * @since CURRENT
12817     */
12818    protected int getRightPaddingOffset() {
12819        return 0;
12820    }
12821
12822    /**
12823     * Amount by which to extend the top fading region. Called only when
12824     * {@link #isPaddingOffsetRequired()} returns true.
12825     *
12826     * @return The top padding offset in pixels.
12827     *
12828     * @see #isPaddingOffsetRequired()
12829     *
12830     * @since CURRENT
12831     */
12832    protected int getTopPaddingOffset() {
12833        return 0;
12834    }
12835
12836    /**
12837     * Amount by which to extend the bottom fading region. Called only when
12838     * {@link #isPaddingOffsetRequired()} returns true.
12839     *
12840     * @return The bottom padding offset in pixels.
12841     *
12842     * @see #isPaddingOffsetRequired()
12843     *
12844     * @since CURRENT
12845     */
12846    protected int getBottomPaddingOffset() {
12847        return 0;
12848    }
12849
12850    /**
12851     * @hide
12852     * @param offsetRequired
12853     */
12854    protected int getFadeTop(boolean offsetRequired) {
12855        int top = mPaddingTop;
12856        if (offsetRequired) top += getTopPaddingOffset();
12857        return top;
12858    }
12859
12860    /**
12861     * @hide
12862     * @param offsetRequired
12863     */
12864    protected int getFadeHeight(boolean offsetRequired) {
12865        int padding = mPaddingTop;
12866        if (offsetRequired) padding += getTopPaddingOffset();
12867        return mBottom - mTop - mPaddingBottom - padding;
12868    }
12869
12870    /**
12871     * <p>Indicates whether this view is attached to a hardware accelerated
12872     * window or not.</p>
12873     *
12874     * <p>Even if this method returns true, it does not mean that every call
12875     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12876     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12877     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12878     * window is hardware accelerated,
12879     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12880     * return false, and this method will return true.</p>
12881     *
12882     * @return True if the view is attached to a window and the window is
12883     *         hardware accelerated; false in any other case.
12884     */
12885    public boolean isHardwareAccelerated() {
12886        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12887    }
12888
12889    /**
12890     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12891     * case of an active Animation being run on the view.
12892     */
12893    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12894            Animation a, boolean scalingRequired) {
12895        Transformation invalidationTransform;
12896        final int flags = parent.mGroupFlags;
12897        final boolean initialized = a.isInitialized();
12898        if (!initialized) {
12899            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12900            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12901            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
12902            onAnimationStart();
12903        }
12904
12905        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12906        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12907            if (parent.mInvalidationTransformation == null) {
12908                parent.mInvalidationTransformation = new Transformation();
12909            }
12910            invalidationTransform = parent.mInvalidationTransformation;
12911            a.getTransformation(drawingTime, invalidationTransform, 1f);
12912        } else {
12913            invalidationTransform = parent.mChildTransformation;
12914        }
12915
12916        if (more) {
12917            if (!a.willChangeBounds()) {
12918                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12919                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12920                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12921                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12922                    // The child need to draw an animation, potentially offscreen, so
12923                    // make sure we do not cancel invalidate requests
12924                    parent.mPrivateFlags |= DRAW_ANIMATION;
12925                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12926                }
12927            } else {
12928                if (parent.mInvalidateRegion == null) {
12929                    parent.mInvalidateRegion = new RectF();
12930                }
12931                final RectF region = parent.mInvalidateRegion;
12932                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12933                        invalidationTransform);
12934
12935                // The child need to draw an animation, potentially offscreen, so
12936                // make sure we do not cancel invalidate requests
12937                parent.mPrivateFlags |= DRAW_ANIMATION;
12938
12939                final int left = mLeft + (int) region.left;
12940                final int top = mTop + (int) region.top;
12941                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12942                        top + (int) (region.height() + .5f));
12943            }
12944        }
12945        return more;
12946    }
12947
12948    /**
12949     * This method is called by getDisplayList() when a display list is created or re-rendered.
12950     * It sets or resets the current value of all properties on that display list (resetting is
12951     * necessary when a display list is being re-created, because we need to make sure that
12952     * previously-set transform values
12953     */
12954    void setDisplayListProperties(DisplayList displayList) {
12955        if (displayList != null) {
12956            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12957            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12958            if (mParent instanceof ViewGroup) {
12959                displayList.setClipChildren(
12960                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12961            }
12962            float alpha = 1;
12963            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12964                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12965                ViewGroup parentVG = (ViewGroup) mParent;
12966                final boolean hasTransform =
12967                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12968                if (hasTransform) {
12969                    Transformation transform = parentVG.mChildTransformation;
12970                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12971                    if (transformType != Transformation.TYPE_IDENTITY) {
12972                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12973                            alpha = transform.getAlpha();
12974                        }
12975                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12976                            displayList.setStaticMatrix(transform.getMatrix());
12977                        }
12978                    }
12979                }
12980            }
12981            if (mTransformationInfo != null) {
12982                alpha *= mTransformationInfo.mAlpha;
12983                if (alpha < 1) {
12984                    final int multipliedAlpha = (int) (255 * alpha);
12985                    if (onSetAlpha(multipliedAlpha)) {
12986                        alpha = 1;
12987                    }
12988                }
12989                displayList.setTransformationInfo(alpha,
12990                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12991                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12992                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12993                        mTransformationInfo.mScaleY);
12994                if (mTransformationInfo.mCamera == null) {
12995                    mTransformationInfo.mCamera = new Camera();
12996                    mTransformationInfo.matrix3D = new Matrix();
12997                }
12998                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12999                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
13000                    displayList.setPivotX(getPivotX());
13001                    displayList.setPivotY(getPivotY());
13002                }
13003            } else if (alpha < 1) {
13004                displayList.setAlpha(alpha);
13005            }
13006        }
13007    }
13008
13009    /**
13010     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13011     * This draw() method is an implementation detail and is not intended to be overridden or
13012     * to be called from anywhere else other than ViewGroup.drawChild().
13013     */
13014    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13015        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13016        boolean more = false;
13017        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13018        final int flags = parent.mGroupFlags;
13019
13020        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13021            parent.mChildTransformation.clear();
13022            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13023        }
13024
13025        Transformation transformToApply = null;
13026        boolean concatMatrix = false;
13027
13028        boolean scalingRequired = false;
13029        boolean caching;
13030        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
13031
13032        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13033        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13034                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13035            caching = true;
13036            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13037            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13038        } else {
13039            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13040        }
13041
13042        final Animation a = getAnimation();
13043        if (a != null) {
13044            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13045            concatMatrix = a.willChangeTransformationMatrix();
13046            if (concatMatrix) {
13047                mPrivateFlags2 |= VIEW_IS_ANIMATING_TRANSFORM;
13048            }
13049            transformToApply = parent.mChildTransformation;
13050        } else {
13051            if ((mPrivateFlags2 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
13052                    mDisplayList != null) {
13053                // No longer animating: clear out old animation matrix
13054                mDisplayList.setAnimationMatrix(null);
13055                mPrivateFlags2 &= ~VIEW_IS_ANIMATING_TRANSFORM;
13056            }
13057            if (!useDisplayListProperties &&
13058                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13059                final boolean hasTransform =
13060                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13061                if (hasTransform) {
13062                    final int transformType = parent.mChildTransformation.getTransformationType();
13063                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13064                            parent.mChildTransformation : null;
13065                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13066                }
13067            }
13068        }
13069
13070        concatMatrix |= !childHasIdentityMatrix;
13071
13072        // Sets the flag as early as possible to allow draw() implementations
13073        // to call invalidate() successfully when doing animations
13074        mPrivateFlags |= DRAWN;
13075
13076        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13077                (mPrivateFlags & DRAW_ANIMATION) == 0) {
13078            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
13079            return more;
13080        }
13081        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
13082
13083        if (hardwareAccelerated) {
13084            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13085            // retain the flag's value temporarily in the mRecreateDisplayList flag
13086            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
13087            mPrivateFlags &= ~INVALIDATED;
13088        }
13089
13090        computeScroll();
13091
13092        final int sx = mScrollX;
13093        final int sy = mScrollY;
13094
13095        DisplayList displayList = null;
13096        Bitmap cache = null;
13097        boolean hasDisplayList = false;
13098        if (caching) {
13099            if (!hardwareAccelerated) {
13100                if (layerType != LAYER_TYPE_NONE) {
13101                    layerType = LAYER_TYPE_SOFTWARE;
13102                    buildDrawingCache(true);
13103                }
13104                cache = getDrawingCache(true);
13105            } else {
13106                switch (layerType) {
13107                    case LAYER_TYPE_SOFTWARE:
13108                        if (useDisplayListProperties) {
13109                            hasDisplayList = canHaveDisplayList();
13110                        } else {
13111                            buildDrawingCache(true);
13112                            cache = getDrawingCache(true);
13113                        }
13114                        break;
13115                    case LAYER_TYPE_HARDWARE:
13116                        if (useDisplayListProperties) {
13117                            hasDisplayList = canHaveDisplayList();
13118                        }
13119                        break;
13120                    case LAYER_TYPE_NONE:
13121                        // Delay getting the display list until animation-driven alpha values are
13122                        // set up and possibly passed on to the view
13123                        hasDisplayList = canHaveDisplayList();
13124                        break;
13125                }
13126            }
13127        }
13128        useDisplayListProperties &= hasDisplayList;
13129        if (useDisplayListProperties) {
13130            displayList = getDisplayList();
13131            if (!displayList.isValid()) {
13132                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13133                // to getDisplayList(), the display list will be marked invalid and we should not
13134                // try to use it again.
13135                displayList = null;
13136                hasDisplayList = false;
13137                useDisplayListProperties = false;
13138            }
13139        }
13140
13141        final boolean hasNoCache = cache == null || hasDisplayList;
13142        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13143                layerType != LAYER_TYPE_HARDWARE;
13144
13145        int restoreTo = -1;
13146        if (!useDisplayListProperties || transformToApply != null) {
13147            restoreTo = canvas.save();
13148        }
13149        if (offsetForScroll) {
13150            canvas.translate(mLeft - sx, mTop - sy);
13151        } else {
13152            if (!useDisplayListProperties) {
13153                canvas.translate(mLeft, mTop);
13154            }
13155            if (scalingRequired) {
13156                if (useDisplayListProperties) {
13157                    // TODO: Might not need this if we put everything inside the DL
13158                    restoreTo = canvas.save();
13159                }
13160                // mAttachInfo cannot be null, otherwise scalingRequired == false
13161                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13162                canvas.scale(scale, scale);
13163            }
13164        }
13165
13166        float alpha = useDisplayListProperties ? 1 : getAlpha();
13167        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix()) {
13168            if (transformToApply != null || !childHasIdentityMatrix) {
13169                int transX = 0;
13170                int transY = 0;
13171
13172                if (offsetForScroll) {
13173                    transX = -sx;
13174                    transY = -sy;
13175                }
13176
13177                if (transformToApply != null) {
13178                    if (concatMatrix) {
13179                        if (useDisplayListProperties) {
13180                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13181                        } else {
13182                            // Undo the scroll translation, apply the transformation matrix,
13183                            // then redo the scroll translate to get the correct result.
13184                            canvas.translate(-transX, -transY);
13185                            canvas.concat(transformToApply.getMatrix());
13186                            canvas.translate(transX, transY);
13187                        }
13188                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13189                    }
13190
13191                    float transformAlpha = transformToApply.getAlpha();
13192                    if (transformAlpha < 1) {
13193                        alpha *= transformToApply.getAlpha();
13194                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13195                    }
13196                }
13197
13198                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13199                    canvas.translate(-transX, -transY);
13200                    canvas.concat(getMatrix());
13201                    canvas.translate(transX, transY);
13202                }
13203            }
13204
13205            if (alpha < 1) {
13206                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13207                if (hasNoCache) {
13208                    final int multipliedAlpha = (int) (255 * alpha);
13209                    if (!onSetAlpha(multipliedAlpha)) {
13210                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13211                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13212                                layerType != LAYER_TYPE_NONE) {
13213                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13214                        }
13215                        if (useDisplayListProperties) {
13216                            displayList.setAlpha(alpha * getAlpha());
13217                        } else  if (layerType == LAYER_TYPE_NONE) {
13218                            final int scrollX = hasDisplayList ? 0 : sx;
13219                            final int scrollY = hasDisplayList ? 0 : sy;
13220                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13221                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13222                        }
13223                    } else {
13224                        // Alpha is handled by the child directly, clobber the layer's alpha
13225                        mPrivateFlags |= ALPHA_SET;
13226                    }
13227                }
13228            }
13229        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13230            onSetAlpha(255);
13231            mPrivateFlags &= ~ALPHA_SET;
13232        }
13233
13234        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13235                !useDisplayListProperties) {
13236            if (offsetForScroll) {
13237                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13238            } else {
13239                if (!scalingRequired || cache == null) {
13240                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13241                } else {
13242                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13243                }
13244            }
13245        }
13246
13247        if (!useDisplayListProperties && hasDisplayList) {
13248            displayList = getDisplayList();
13249            if (!displayList.isValid()) {
13250                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13251                // to getDisplayList(), the display list will be marked invalid and we should not
13252                // try to use it again.
13253                displayList = null;
13254                hasDisplayList = false;
13255            }
13256        }
13257
13258        if (hasNoCache) {
13259            boolean layerRendered = false;
13260            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13261                final HardwareLayer layer = getHardwareLayer();
13262                if (layer != null && layer.isValid()) {
13263                    mLayerPaint.setAlpha((int) (alpha * 255));
13264                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13265                    layerRendered = true;
13266                } else {
13267                    final int scrollX = hasDisplayList ? 0 : sx;
13268                    final int scrollY = hasDisplayList ? 0 : sy;
13269                    canvas.saveLayer(scrollX, scrollY,
13270                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13271                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13272                }
13273            }
13274
13275            if (!layerRendered) {
13276                if (!hasDisplayList) {
13277                    // Fast path for layouts with no backgrounds
13278                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13279                        mPrivateFlags &= ~DIRTY_MASK;
13280                        dispatchDraw(canvas);
13281                    } else {
13282                        draw(canvas);
13283                    }
13284                } else {
13285                    mPrivateFlags &= ~DIRTY_MASK;
13286                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13287                }
13288            }
13289        } else if (cache != null) {
13290            mPrivateFlags &= ~DIRTY_MASK;
13291            Paint cachePaint;
13292
13293            if (layerType == LAYER_TYPE_NONE) {
13294                cachePaint = parent.mCachePaint;
13295                if (cachePaint == null) {
13296                    cachePaint = new Paint();
13297                    cachePaint.setDither(false);
13298                    parent.mCachePaint = cachePaint;
13299                }
13300                if (alpha < 1) {
13301                    cachePaint.setAlpha((int) (alpha * 255));
13302                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13303                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13304                    cachePaint.setAlpha(255);
13305                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13306                }
13307            } else {
13308                cachePaint = mLayerPaint;
13309                cachePaint.setAlpha((int) (alpha * 255));
13310            }
13311            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13312        }
13313
13314        if (restoreTo >= 0) {
13315            canvas.restoreToCount(restoreTo);
13316        }
13317
13318        if (a != null && !more) {
13319            if (!hardwareAccelerated && !a.getFillAfter()) {
13320                onSetAlpha(255);
13321            }
13322            parent.finishAnimatingView(this, a);
13323        }
13324
13325        if (more && hardwareAccelerated) {
13326            // invalidation is the trigger to recreate display lists, so if we're using
13327            // display lists to render, force an invalidate to allow the animation to
13328            // continue drawing another frame
13329            parent.invalidate(true);
13330            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13331                // alpha animations should cause the child to recreate its display list
13332                invalidate(true);
13333            }
13334        }
13335
13336        mRecreateDisplayList = false;
13337
13338        return more;
13339    }
13340
13341    /**
13342     * Manually render this view (and all of its children) to the given Canvas.
13343     * The view must have already done a full layout before this function is
13344     * called.  When implementing a view, implement
13345     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13346     * If you do need to override this method, call the superclass version.
13347     *
13348     * @param canvas The Canvas to which the View is rendered.
13349     */
13350    public void draw(Canvas canvas) {
13351        final int privateFlags = mPrivateFlags;
13352        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13353                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13354        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13355
13356        /*
13357         * Draw traversal performs several drawing steps which must be executed
13358         * in the appropriate order:
13359         *
13360         *      1. Draw the background
13361         *      2. If necessary, save the canvas' layers to prepare for fading
13362         *      3. Draw view's content
13363         *      4. Draw children
13364         *      5. If necessary, draw the fading edges and restore layers
13365         *      6. Draw decorations (scrollbars for instance)
13366         */
13367
13368        // Step 1, draw the background, if needed
13369        int saveCount;
13370
13371        if (!dirtyOpaque) {
13372            final Drawable background = mBackground;
13373            if (background != null) {
13374                final int scrollX = mScrollX;
13375                final int scrollY = mScrollY;
13376
13377                if (mBackgroundSizeChanged) {
13378                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13379                    mBackgroundSizeChanged = false;
13380                }
13381
13382                if ((scrollX | scrollY) == 0) {
13383                    background.draw(canvas);
13384                } else {
13385                    canvas.translate(scrollX, scrollY);
13386                    background.draw(canvas);
13387                    canvas.translate(-scrollX, -scrollY);
13388                }
13389            }
13390        }
13391
13392        // skip step 2 & 5 if possible (common case)
13393        final int viewFlags = mViewFlags;
13394        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13395        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13396        if (!verticalEdges && !horizontalEdges) {
13397            // Step 3, draw the content
13398            if (!dirtyOpaque) onDraw(canvas);
13399
13400            // Step 4, draw the children
13401            dispatchDraw(canvas);
13402
13403            // Step 6, draw decorations (scrollbars)
13404            onDrawScrollBars(canvas);
13405
13406            // we're done...
13407            return;
13408        }
13409
13410        /*
13411         * Here we do the full fledged routine...
13412         * (this is an uncommon case where speed matters less,
13413         * this is why we repeat some of the tests that have been
13414         * done above)
13415         */
13416
13417        boolean drawTop = false;
13418        boolean drawBottom = false;
13419        boolean drawLeft = false;
13420        boolean drawRight = false;
13421
13422        float topFadeStrength = 0.0f;
13423        float bottomFadeStrength = 0.0f;
13424        float leftFadeStrength = 0.0f;
13425        float rightFadeStrength = 0.0f;
13426
13427        // Step 2, save the canvas' layers
13428        int paddingLeft = mPaddingLeft;
13429
13430        final boolean offsetRequired = isPaddingOffsetRequired();
13431        if (offsetRequired) {
13432            paddingLeft += getLeftPaddingOffset();
13433        }
13434
13435        int left = mScrollX + paddingLeft;
13436        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13437        int top = mScrollY + getFadeTop(offsetRequired);
13438        int bottom = top + getFadeHeight(offsetRequired);
13439
13440        if (offsetRequired) {
13441            right += getRightPaddingOffset();
13442            bottom += getBottomPaddingOffset();
13443        }
13444
13445        final ScrollabilityCache scrollabilityCache = mScrollCache;
13446        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13447        int length = (int) fadeHeight;
13448
13449        // clip the fade length if top and bottom fades overlap
13450        // overlapping fades produce odd-looking artifacts
13451        if (verticalEdges && (top + length > bottom - length)) {
13452            length = (bottom - top) / 2;
13453        }
13454
13455        // also clip horizontal fades if necessary
13456        if (horizontalEdges && (left + length > right - length)) {
13457            length = (right - left) / 2;
13458        }
13459
13460        if (verticalEdges) {
13461            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13462            drawTop = topFadeStrength * fadeHeight > 1.0f;
13463            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13464            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13465        }
13466
13467        if (horizontalEdges) {
13468            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13469            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13470            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13471            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13472        }
13473
13474        saveCount = canvas.getSaveCount();
13475
13476        int solidColor = getSolidColor();
13477        if (solidColor == 0) {
13478            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13479
13480            if (drawTop) {
13481                canvas.saveLayer(left, top, right, top + length, null, flags);
13482            }
13483
13484            if (drawBottom) {
13485                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13486            }
13487
13488            if (drawLeft) {
13489                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13490            }
13491
13492            if (drawRight) {
13493                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13494            }
13495        } else {
13496            scrollabilityCache.setFadeColor(solidColor);
13497        }
13498
13499        // Step 3, draw the content
13500        if (!dirtyOpaque) onDraw(canvas);
13501
13502        // Step 4, draw the children
13503        dispatchDraw(canvas);
13504
13505        // Step 5, draw the fade effect and restore layers
13506        final Paint p = scrollabilityCache.paint;
13507        final Matrix matrix = scrollabilityCache.matrix;
13508        final Shader fade = scrollabilityCache.shader;
13509
13510        if (drawTop) {
13511            matrix.setScale(1, fadeHeight * topFadeStrength);
13512            matrix.postTranslate(left, top);
13513            fade.setLocalMatrix(matrix);
13514            canvas.drawRect(left, top, right, top + length, p);
13515        }
13516
13517        if (drawBottom) {
13518            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13519            matrix.postRotate(180);
13520            matrix.postTranslate(left, bottom);
13521            fade.setLocalMatrix(matrix);
13522            canvas.drawRect(left, bottom - length, right, bottom, p);
13523        }
13524
13525        if (drawLeft) {
13526            matrix.setScale(1, fadeHeight * leftFadeStrength);
13527            matrix.postRotate(-90);
13528            matrix.postTranslate(left, top);
13529            fade.setLocalMatrix(matrix);
13530            canvas.drawRect(left, top, left + length, bottom, p);
13531        }
13532
13533        if (drawRight) {
13534            matrix.setScale(1, fadeHeight * rightFadeStrength);
13535            matrix.postRotate(90);
13536            matrix.postTranslate(right, top);
13537            fade.setLocalMatrix(matrix);
13538            canvas.drawRect(right - length, top, right, bottom, p);
13539        }
13540
13541        canvas.restoreToCount(saveCount);
13542
13543        // Step 6, draw decorations (scrollbars)
13544        onDrawScrollBars(canvas);
13545    }
13546
13547    /**
13548     * Override this if your view is known to always be drawn on top of a solid color background,
13549     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13550     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13551     * should be set to 0xFF.
13552     *
13553     * @see #setVerticalFadingEdgeEnabled(boolean)
13554     * @see #setHorizontalFadingEdgeEnabled(boolean)
13555     *
13556     * @return The known solid color background for this view, or 0 if the color may vary
13557     */
13558    @ViewDebug.ExportedProperty(category = "drawing")
13559    public int getSolidColor() {
13560        return 0;
13561    }
13562
13563    /**
13564     * Build a human readable string representation of the specified view flags.
13565     *
13566     * @param flags the view flags to convert to a string
13567     * @return a String representing the supplied flags
13568     */
13569    private static String printFlags(int flags) {
13570        String output = "";
13571        int numFlags = 0;
13572        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13573            output += "TAKES_FOCUS";
13574            numFlags++;
13575        }
13576
13577        switch (flags & VISIBILITY_MASK) {
13578        case INVISIBLE:
13579            if (numFlags > 0) {
13580                output += " ";
13581            }
13582            output += "INVISIBLE";
13583            // USELESS HERE numFlags++;
13584            break;
13585        case GONE:
13586            if (numFlags > 0) {
13587                output += " ";
13588            }
13589            output += "GONE";
13590            // USELESS HERE numFlags++;
13591            break;
13592        default:
13593            break;
13594        }
13595        return output;
13596    }
13597
13598    /**
13599     * Build a human readable string representation of the specified private
13600     * view flags.
13601     *
13602     * @param privateFlags the private view flags to convert to a string
13603     * @return a String representing the supplied flags
13604     */
13605    private static String printPrivateFlags(int privateFlags) {
13606        String output = "";
13607        int numFlags = 0;
13608
13609        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13610            output += "WANTS_FOCUS";
13611            numFlags++;
13612        }
13613
13614        if ((privateFlags & FOCUSED) == FOCUSED) {
13615            if (numFlags > 0) {
13616                output += " ";
13617            }
13618            output += "FOCUSED";
13619            numFlags++;
13620        }
13621
13622        if ((privateFlags & SELECTED) == SELECTED) {
13623            if (numFlags > 0) {
13624                output += " ";
13625            }
13626            output += "SELECTED";
13627            numFlags++;
13628        }
13629
13630        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13631            if (numFlags > 0) {
13632                output += " ";
13633            }
13634            output += "IS_ROOT_NAMESPACE";
13635            numFlags++;
13636        }
13637
13638        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13639            if (numFlags > 0) {
13640                output += " ";
13641            }
13642            output += "HAS_BOUNDS";
13643            numFlags++;
13644        }
13645
13646        if ((privateFlags & DRAWN) == DRAWN) {
13647            if (numFlags > 0) {
13648                output += " ";
13649            }
13650            output += "DRAWN";
13651            // USELESS HERE numFlags++;
13652        }
13653        return output;
13654    }
13655
13656    /**
13657     * <p>Indicates whether or not this view's layout will be requested during
13658     * the next hierarchy layout pass.</p>
13659     *
13660     * @return true if the layout will be forced during next layout pass
13661     */
13662    public boolean isLayoutRequested() {
13663        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13664    }
13665
13666    /**
13667     * Assign a size and position to a view and all of its
13668     * descendants
13669     *
13670     * <p>This is the second phase of the layout mechanism.
13671     * (The first is measuring). In this phase, each parent calls
13672     * layout on all of its children to position them.
13673     * This is typically done using the child measurements
13674     * that were stored in the measure pass().</p>
13675     *
13676     * <p>Derived classes should not override this method.
13677     * Derived classes with children should override
13678     * onLayout. In that method, they should
13679     * call layout on each of their children.</p>
13680     *
13681     * @param l Left position, relative to parent
13682     * @param t Top position, relative to parent
13683     * @param r Right position, relative to parent
13684     * @param b Bottom position, relative to parent
13685     */
13686    @SuppressWarnings({"unchecked"})
13687    public void layout(int l, int t, int r, int b) {
13688        int oldL = mLeft;
13689        int oldT = mTop;
13690        int oldB = mBottom;
13691        int oldR = mRight;
13692        boolean changed = setFrame(l, t, r, b);
13693        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13694            onLayout(changed, l, t, r, b);
13695            mPrivateFlags &= ~LAYOUT_REQUIRED;
13696
13697            ListenerInfo li = mListenerInfo;
13698            if (li != null && li.mOnLayoutChangeListeners != null) {
13699                ArrayList<OnLayoutChangeListener> listenersCopy =
13700                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13701                int numListeners = listenersCopy.size();
13702                for (int i = 0; i < numListeners; ++i) {
13703                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13704                }
13705            }
13706        }
13707        mPrivateFlags &= ~FORCE_LAYOUT;
13708    }
13709
13710    /**
13711     * Called from layout when this view should
13712     * assign a size and position to each of its children.
13713     *
13714     * Derived classes with children should override
13715     * this method and call layout on each of
13716     * their children.
13717     * @param changed This is a new size or position for this view
13718     * @param left Left position, relative to parent
13719     * @param top Top position, relative to parent
13720     * @param right Right position, relative to parent
13721     * @param bottom Bottom position, relative to parent
13722     */
13723    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13724    }
13725
13726    /**
13727     * Assign a size and position to this view.
13728     *
13729     * This is called from layout.
13730     *
13731     * @param left Left position, relative to parent
13732     * @param top Top position, relative to parent
13733     * @param right Right position, relative to parent
13734     * @param bottom Bottom position, relative to parent
13735     * @return true if the new size and position are different than the
13736     *         previous ones
13737     * {@hide}
13738     */
13739    protected boolean setFrame(int left, int top, int right, int bottom) {
13740        boolean changed = false;
13741
13742        if (DBG) {
13743            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13744                    + right + "," + bottom + ")");
13745        }
13746
13747        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13748            changed = true;
13749
13750            // Remember our drawn bit
13751            int drawn = mPrivateFlags & DRAWN;
13752
13753            int oldWidth = mRight - mLeft;
13754            int oldHeight = mBottom - mTop;
13755            int newWidth = right - left;
13756            int newHeight = bottom - top;
13757            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13758
13759            // Invalidate our old position
13760            invalidate(sizeChanged);
13761
13762            mLeft = left;
13763            mTop = top;
13764            mRight = right;
13765            mBottom = bottom;
13766            if (mDisplayList != null) {
13767                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13768            }
13769
13770            mPrivateFlags |= HAS_BOUNDS;
13771
13772
13773            if (sizeChanged) {
13774                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13775                    // A change in dimension means an auto-centered pivot point changes, too
13776                    if (mTransformationInfo != null) {
13777                        mTransformationInfo.mMatrixDirty = true;
13778                    }
13779                }
13780                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13781            }
13782
13783            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13784                // If we are visible, force the DRAWN bit to on so that
13785                // this invalidate will go through (at least to our parent).
13786                // This is because someone may have invalidated this view
13787                // before this call to setFrame came in, thereby clearing
13788                // the DRAWN bit.
13789                mPrivateFlags |= DRAWN;
13790                invalidate(sizeChanged);
13791                // parent display list may need to be recreated based on a change in the bounds
13792                // of any child
13793                invalidateParentCaches();
13794            }
13795
13796            // Reset drawn bit to original value (invalidate turns it off)
13797            mPrivateFlags |= drawn;
13798
13799            mBackgroundSizeChanged = true;
13800        }
13801        return changed;
13802    }
13803
13804    /**
13805     * Finalize inflating a view from XML.  This is called as the last phase
13806     * of inflation, after all child views have been added.
13807     *
13808     * <p>Even if the subclass overrides onFinishInflate, they should always be
13809     * sure to call the super method, so that we get called.
13810     */
13811    protected void onFinishInflate() {
13812    }
13813
13814    /**
13815     * Returns the resources associated with this view.
13816     *
13817     * @return Resources object.
13818     */
13819    public Resources getResources() {
13820        return mResources;
13821    }
13822
13823    /**
13824     * Invalidates the specified Drawable.
13825     *
13826     * @param drawable the drawable to invalidate
13827     */
13828    public void invalidateDrawable(Drawable drawable) {
13829        if (verifyDrawable(drawable)) {
13830            final Rect dirty = drawable.getBounds();
13831            final int scrollX = mScrollX;
13832            final int scrollY = mScrollY;
13833
13834            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13835                    dirty.right + scrollX, dirty.bottom + scrollY);
13836        }
13837    }
13838
13839    /**
13840     * Schedules an action on a drawable to occur at a specified time.
13841     *
13842     * @param who the recipient of the action
13843     * @param what the action to run on the drawable
13844     * @param when the time at which the action must occur. Uses the
13845     *        {@link SystemClock#uptimeMillis} timebase.
13846     */
13847    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13848        if (verifyDrawable(who) && what != null) {
13849            final long delay = when - SystemClock.uptimeMillis();
13850            if (mAttachInfo != null) {
13851                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13852                        Choreographer.CALLBACK_ANIMATION, what, who,
13853                        Choreographer.subtractFrameDelay(delay));
13854            } else {
13855                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13856            }
13857        }
13858    }
13859
13860    /**
13861     * Cancels a scheduled action on a drawable.
13862     *
13863     * @param who the recipient of the action
13864     * @param what the action to cancel
13865     */
13866    public void unscheduleDrawable(Drawable who, Runnable what) {
13867        if (verifyDrawable(who) && what != null) {
13868            if (mAttachInfo != null) {
13869                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13870                        Choreographer.CALLBACK_ANIMATION, what, who);
13871            } else {
13872                ViewRootImpl.getRunQueue().removeCallbacks(what);
13873            }
13874        }
13875    }
13876
13877    /**
13878     * Unschedule any events associated with the given Drawable.  This can be
13879     * used when selecting a new Drawable into a view, so that the previous
13880     * one is completely unscheduled.
13881     *
13882     * @param who The Drawable to unschedule.
13883     *
13884     * @see #drawableStateChanged
13885     */
13886    public void unscheduleDrawable(Drawable who) {
13887        if (mAttachInfo != null && who != null) {
13888            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13889                    Choreographer.CALLBACK_ANIMATION, null, who);
13890        }
13891    }
13892
13893    /**
13894    * Return the layout direction of a given Drawable.
13895    *
13896    * @param who the Drawable to query
13897    * @hide
13898    */
13899    public int getResolvedLayoutDirection(Drawable who) {
13900        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13901    }
13902
13903    /**
13904     * If your view subclass is displaying its own Drawable objects, it should
13905     * override this function and return true for any Drawable it is
13906     * displaying.  This allows animations for those drawables to be
13907     * scheduled.
13908     *
13909     * <p>Be sure to call through to the super class when overriding this
13910     * function.
13911     *
13912     * @param who The Drawable to verify.  Return true if it is one you are
13913     *            displaying, else return the result of calling through to the
13914     *            super class.
13915     *
13916     * @return boolean If true than the Drawable is being displayed in the
13917     *         view; else false and it is not allowed to animate.
13918     *
13919     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13920     * @see #drawableStateChanged()
13921     */
13922    protected boolean verifyDrawable(Drawable who) {
13923        return who == mBackground;
13924    }
13925
13926    /**
13927     * This function is called whenever the state of the view changes in such
13928     * a way that it impacts the state of drawables being shown.
13929     *
13930     * <p>Be sure to call through to the superclass when overriding this
13931     * function.
13932     *
13933     * @see Drawable#setState(int[])
13934     */
13935    protected void drawableStateChanged() {
13936        Drawable d = mBackground;
13937        if (d != null && d.isStateful()) {
13938            d.setState(getDrawableState());
13939        }
13940    }
13941
13942    /**
13943     * Call this to force a view to update its drawable state. This will cause
13944     * drawableStateChanged to be called on this view. Views that are interested
13945     * in the new state should call getDrawableState.
13946     *
13947     * @see #drawableStateChanged
13948     * @see #getDrawableState
13949     */
13950    public void refreshDrawableState() {
13951        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13952        drawableStateChanged();
13953
13954        ViewParent parent = mParent;
13955        if (parent != null) {
13956            parent.childDrawableStateChanged(this);
13957        }
13958    }
13959
13960    /**
13961     * Return an array of resource IDs of the drawable states representing the
13962     * current state of the view.
13963     *
13964     * @return The current drawable state
13965     *
13966     * @see Drawable#setState(int[])
13967     * @see #drawableStateChanged()
13968     * @see #onCreateDrawableState(int)
13969     */
13970    public final int[] getDrawableState() {
13971        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13972            return mDrawableState;
13973        } else {
13974            mDrawableState = onCreateDrawableState(0);
13975            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13976            return mDrawableState;
13977        }
13978    }
13979
13980    /**
13981     * Generate the new {@link android.graphics.drawable.Drawable} state for
13982     * this view. This is called by the view
13983     * system when the cached Drawable state is determined to be invalid.  To
13984     * retrieve the current state, you should use {@link #getDrawableState}.
13985     *
13986     * @param extraSpace if non-zero, this is the number of extra entries you
13987     * would like in the returned array in which you can place your own
13988     * states.
13989     *
13990     * @return Returns an array holding the current {@link Drawable} state of
13991     * the view.
13992     *
13993     * @see #mergeDrawableStates(int[], int[])
13994     */
13995    protected int[] onCreateDrawableState(int extraSpace) {
13996        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13997                mParent instanceof View) {
13998            return ((View) mParent).onCreateDrawableState(extraSpace);
13999        }
14000
14001        int[] drawableState;
14002
14003        int privateFlags = mPrivateFlags;
14004
14005        int viewStateIndex = 0;
14006        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14007        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14008        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14009        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14010        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14011        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14012        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14013                HardwareRenderer.isAvailable()) {
14014            // This is set if HW acceleration is requested, even if the current
14015            // process doesn't allow it.  This is just to allow app preview
14016            // windows to better match their app.
14017            viewStateIndex |= VIEW_STATE_ACCELERATED;
14018        }
14019        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14020
14021        final int privateFlags2 = mPrivateFlags2;
14022        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14023        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14024
14025        drawableState = VIEW_STATE_SETS[viewStateIndex];
14026
14027        //noinspection ConstantIfStatement
14028        if (false) {
14029            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14030            Log.i("View", toString()
14031                    + " pressed=" + ((privateFlags & PRESSED) != 0)
14032                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14033                    + " fo=" + hasFocus()
14034                    + " sl=" + ((privateFlags & SELECTED) != 0)
14035                    + " wf=" + hasWindowFocus()
14036                    + ": " + Arrays.toString(drawableState));
14037        }
14038
14039        if (extraSpace == 0) {
14040            return drawableState;
14041        }
14042
14043        final int[] fullState;
14044        if (drawableState != null) {
14045            fullState = new int[drawableState.length + extraSpace];
14046            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14047        } else {
14048            fullState = new int[extraSpace];
14049        }
14050
14051        return fullState;
14052    }
14053
14054    /**
14055     * Merge your own state values in <var>additionalState</var> into the base
14056     * state values <var>baseState</var> that were returned by
14057     * {@link #onCreateDrawableState(int)}.
14058     *
14059     * @param baseState The base state values returned by
14060     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14061     * own additional state values.
14062     *
14063     * @param additionalState The additional state values you would like
14064     * added to <var>baseState</var>; this array is not modified.
14065     *
14066     * @return As a convenience, the <var>baseState</var> array you originally
14067     * passed into the function is returned.
14068     *
14069     * @see #onCreateDrawableState(int)
14070     */
14071    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14072        final int N = baseState.length;
14073        int i = N - 1;
14074        while (i >= 0 && baseState[i] == 0) {
14075            i--;
14076        }
14077        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14078        return baseState;
14079    }
14080
14081    /**
14082     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14083     * on all Drawable objects associated with this view.
14084     */
14085    public void jumpDrawablesToCurrentState() {
14086        if (mBackground != null) {
14087            mBackground.jumpToCurrentState();
14088        }
14089    }
14090
14091    /**
14092     * Sets the background color for this view.
14093     * @param color the color of the background
14094     */
14095    @RemotableViewMethod
14096    public void setBackgroundColor(int color) {
14097        if (mBackground instanceof ColorDrawable) {
14098            ((ColorDrawable) mBackground).setColor(color);
14099        } else {
14100            setBackground(new ColorDrawable(color));
14101        }
14102    }
14103
14104    /**
14105     * Set the background to a given resource. The resource should refer to
14106     * a Drawable object or 0 to remove the background.
14107     * @param resid The identifier of the resource.
14108     *
14109     * @attr ref android.R.styleable#View_background
14110     */
14111    @RemotableViewMethod
14112    public void setBackgroundResource(int resid) {
14113        if (resid != 0 && resid == mBackgroundResource) {
14114            return;
14115        }
14116
14117        Drawable d= null;
14118        if (resid != 0) {
14119            d = mResources.getDrawable(resid);
14120        }
14121        setBackground(d);
14122
14123        mBackgroundResource = resid;
14124    }
14125
14126    /**
14127     * Set the background to a given Drawable, or remove the background. If the
14128     * background has padding, this View's padding is set to the background's
14129     * padding. However, when a background is removed, this View's padding isn't
14130     * touched. If setting the padding is desired, please use
14131     * {@link #setPadding(int, int, int, int)}.
14132     *
14133     * @param background The Drawable to use as the background, or null to remove the
14134     *        background
14135     */
14136    public void setBackground(Drawable background) {
14137        //noinspection deprecation
14138        setBackgroundDrawable(background);
14139    }
14140
14141    /**
14142     * @deprecated use {@link #setBackground(Drawable)} instead
14143     */
14144    @Deprecated
14145    public void setBackgroundDrawable(Drawable background) {
14146        if (background == mBackground) {
14147            return;
14148        }
14149
14150        boolean requestLayout = false;
14151
14152        mBackgroundResource = 0;
14153
14154        /*
14155         * Regardless of whether we're setting a new background or not, we want
14156         * to clear the previous drawable.
14157         */
14158        if (mBackground != null) {
14159            mBackground.setCallback(null);
14160            unscheduleDrawable(mBackground);
14161        }
14162
14163        if (background != null) {
14164            Rect padding = sThreadLocal.get();
14165            if (padding == null) {
14166                padding = new Rect();
14167                sThreadLocal.set(padding);
14168            }
14169            if (background.getPadding(padding)) {
14170                switch (background.getResolvedLayoutDirectionSelf()) {
14171                    case LAYOUT_DIRECTION_RTL:
14172                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
14173                        break;
14174                    case LAYOUT_DIRECTION_LTR:
14175                    default:
14176                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
14177                }
14178            }
14179
14180            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14181            // if it has a different minimum size, we should layout again
14182            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14183                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14184                requestLayout = true;
14185            }
14186
14187            background.setCallback(this);
14188            if (background.isStateful()) {
14189                background.setState(getDrawableState());
14190            }
14191            background.setVisible(getVisibility() == VISIBLE, false);
14192            mBackground = background;
14193
14194            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14195                mPrivateFlags &= ~SKIP_DRAW;
14196                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14197                requestLayout = true;
14198            }
14199        } else {
14200            /* Remove the background */
14201            mBackground = null;
14202
14203            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14204                /*
14205                 * This view ONLY drew the background before and we're removing
14206                 * the background, so now it won't draw anything
14207                 * (hence we SKIP_DRAW)
14208                 */
14209                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14210                mPrivateFlags |= SKIP_DRAW;
14211            }
14212
14213            /*
14214             * When the background is set, we try to apply its padding to this
14215             * View. When the background is removed, we don't touch this View's
14216             * padding. This is noted in the Javadocs. Hence, we don't need to
14217             * requestLayout(), the invalidate() below is sufficient.
14218             */
14219
14220            // The old background's minimum size could have affected this
14221            // View's layout, so let's requestLayout
14222            requestLayout = true;
14223        }
14224
14225        computeOpaqueFlags();
14226
14227        if (requestLayout) {
14228            requestLayout();
14229        }
14230
14231        mBackgroundSizeChanged = true;
14232        invalidate(true);
14233    }
14234
14235    /**
14236     * Gets the background drawable
14237     *
14238     * @return The drawable used as the background for this view, if any.
14239     *
14240     * @see #setBackground(Drawable)
14241     *
14242     * @attr ref android.R.styleable#View_background
14243     */
14244    public Drawable getBackground() {
14245        return mBackground;
14246    }
14247
14248    /**
14249     * Sets the padding. The view may add on the space required to display
14250     * the scrollbars, depending on the style and visibility of the scrollbars.
14251     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14252     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14253     * from the values set in this call.
14254     *
14255     * @attr ref android.R.styleable#View_padding
14256     * @attr ref android.R.styleable#View_paddingBottom
14257     * @attr ref android.R.styleable#View_paddingLeft
14258     * @attr ref android.R.styleable#View_paddingRight
14259     * @attr ref android.R.styleable#View_paddingTop
14260     * @param left the left padding in pixels
14261     * @param top the top padding in pixels
14262     * @param right the right padding in pixels
14263     * @param bottom the bottom padding in pixels
14264     */
14265    public void setPadding(int left, int top, int right, int bottom) {
14266        mUserPaddingStart = -1;
14267        mUserPaddingEnd = -1;
14268        mUserPaddingRelative = false;
14269
14270        internalSetPadding(left, top, right, bottom);
14271    }
14272
14273    private void internalSetPadding(int left, int top, int right, int bottom) {
14274        mUserPaddingLeft = left;
14275        mUserPaddingRight = right;
14276        mUserPaddingBottom = bottom;
14277
14278        final int viewFlags = mViewFlags;
14279        boolean changed = false;
14280
14281        // Common case is there are no scroll bars.
14282        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14283            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14284                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14285                        ? 0 : getVerticalScrollbarWidth();
14286                switch (mVerticalScrollbarPosition) {
14287                    case SCROLLBAR_POSITION_DEFAULT:
14288                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14289                            left += offset;
14290                        } else {
14291                            right += offset;
14292                        }
14293                        break;
14294                    case SCROLLBAR_POSITION_RIGHT:
14295                        right += offset;
14296                        break;
14297                    case SCROLLBAR_POSITION_LEFT:
14298                        left += offset;
14299                        break;
14300                }
14301            }
14302            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14303                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14304                        ? 0 : getHorizontalScrollbarHeight();
14305            }
14306        }
14307
14308        if (mPaddingLeft != left) {
14309            changed = true;
14310            mPaddingLeft = left;
14311        }
14312        if (mPaddingTop != top) {
14313            changed = true;
14314            mPaddingTop = top;
14315        }
14316        if (mPaddingRight != right) {
14317            changed = true;
14318            mPaddingRight = right;
14319        }
14320        if (mPaddingBottom != bottom) {
14321            changed = true;
14322            mPaddingBottom = bottom;
14323        }
14324
14325        if (changed) {
14326            requestLayout();
14327        }
14328    }
14329
14330    /**
14331     * Sets the relative padding. The view may add on the space required to display
14332     * the scrollbars, depending on the style and visibility of the scrollbars.
14333     * from the values set in this call.
14334     *
14335     * @param start the start padding in pixels
14336     * @param top the top padding in pixels
14337     * @param end the end padding in pixels
14338     * @param bottom the bottom padding in pixels
14339     * @hide
14340     */
14341    public void setPaddingRelative(int start, int top, int end, int bottom) {
14342        mUserPaddingStart = start;
14343        mUserPaddingEnd = end;
14344        mUserPaddingRelative = true;
14345
14346        switch(getResolvedLayoutDirection()) {
14347            case LAYOUT_DIRECTION_RTL:
14348                internalSetPadding(end, top, start, bottom);
14349                break;
14350            case LAYOUT_DIRECTION_LTR:
14351            default:
14352                internalSetPadding(start, top, end, bottom);
14353        }
14354    }
14355
14356    /**
14357     * Returns the top padding of this view.
14358     *
14359     * @return the top padding in pixels
14360     */
14361    public int getPaddingTop() {
14362        return mPaddingTop;
14363    }
14364
14365    /**
14366     * Returns the bottom padding of this view. If there are inset and enabled
14367     * scrollbars, this value may include the space required to display the
14368     * scrollbars as well.
14369     *
14370     * @return the bottom padding in pixels
14371     */
14372    public int getPaddingBottom() {
14373        return mPaddingBottom;
14374    }
14375
14376    /**
14377     * Returns the left padding of this view. If there are inset and enabled
14378     * scrollbars, this value may include the space required to display the
14379     * scrollbars as well.
14380     *
14381     * @return the left padding in pixels
14382     */
14383    public int getPaddingLeft() {
14384        return mPaddingLeft;
14385    }
14386
14387    /**
14388     * Returns the start padding of this view depending on its resolved layout direction.
14389     * If there are inset and enabled scrollbars, this value may include the space
14390     * required to display the scrollbars as well.
14391     *
14392     * @return the start padding in pixels
14393     * @hide
14394     */
14395    public int getPaddingStart() {
14396        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14397                mPaddingRight : mPaddingLeft;
14398    }
14399
14400    /**
14401     * Returns the right padding of this view. If there are inset and enabled
14402     * scrollbars, this value may include the space required to display the
14403     * scrollbars as well.
14404     *
14405     * @return the right padding in pixels
14406     */
14407    public int getPaddingRight() {
14408        return mPaddingRight;
14409    }
14410
14411    /**
14412     * Returns the end padding of this view depending on its resolved layout direction.
14413     * If there are inset and enabled scrollbars, this value may include the space
14414     * required to display the scrollbars as well.
14415     *
14416     * @return the end padding in pixels
14417     * @hide
14418     */
14419    public int getPaddingEnd() {
14420        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14421                mPaddingLeft : mPaddingRight;
14422    }
14423
14424    /**
14425     * Return if the padding as been set thru relative values
14426     * {@link #setPaddingRelative(int, int, int, int)}
14427     *
14428     * @return true if the padding is relative or false if it is not.
14429     * @hide
14430     */
14431    public boolean isPaddingRelative() {
14432        return mUserPaddingRelative;
14433    }
14434
14435    /**
14436     * @hide
14437     */
14438    public Insets getOpticalInsets() {
14439        if (mLayoutInsets == null) {
14440            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14441        }
14442        return mLayoutInsets;
14443    }
14444
14445    /**
14446     * @hide
14447     */
14448    public void setLayoutInsets(Insets layoutInsets) {
14449        mLayoutInsets = layoutInsets;
14450    }
14451
14452    /**
14453     * Changes the selection state of this view. A view can be selected or not.
14454     * Note that selection is not the same as focus. Views are typically
14455     * selected in the context of an AdapterView like ListView or GridView;
14456     * the selected view is the view that is highlighted.
14457     *
14458     * @param selected true if the view must be selected, false otherwise
14459     */
14460    public void setSelected(boolean selected) {
14461        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14462            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14463            if (!selected) resetPressedState();
14464            invalidate(true);
14465            refreshDrawableState();
14466            dispatchSetSelected(selected);
14467            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14468                notifyAccessibilityStateChanged();
14469            }
14470        }
14471    }
14472
14473    /**
14474     * Dispatch setSelected to all of this View's children.
14475     *
14476     * @see #setSelected(boolean)
14477     *
14478     * @param selected The new selected state
14479     */
14480    protected void dispatchSetSelected(boolean selected) {
14481    }
14482
14483    /**
14484     * Indicates the selection state of this view.
14485     *
14486     * @return true if the view is selected, false otherwise
14487     */
14488    @ViewDebug.ExportedProperty
14489    public boolean isSelected() {
14490        return (mPrivateFlags & SELECTED) != 0;
14491    }
14492
14493    /**
14494     * Changes the activated state of this view. A view can be activated or not.
14495     * Note that activation is not the same as selection.  Selection is
14496     * a transient property, representing the view (hierarchy) the user is
14497     * currently interacting with.  Activation is a longer-term state that the
14498     * user can move views in and out of.  For example, in a list view with
14499     * single or multiple selection enabled, the views in the current selection
14500     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14501     * here.)  The activated state is propagated down to children of the view it
14502     * is set on.
14503     *
14504     * @param activated true if the view must be activated, false otherwise
14505     */
14506    public void setActivated(boolean activated) {
14507        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14508            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14509            invalidate(true);
14510            refreshDrawableState();
14511            dispatchSetActivated(activated);
14512        }
14513    }
14514
14515    /**
14516     * Dispatch setActivated to all of this View's children.
14517     *
14518     * @see #setActivated(boolean)
14519     *
14520     * @param activated The new activated state
14521     */
14522    protected void dispatchSetActivated(boolean activated) {
14523    }
14524
14525    /**
14526     * Indicates the activation state of this view.
14527     *
14528     * @return true if the view is activated, false otherwise
14529     */
14530    @ViewDebug.ExportedProperty
14531    public boolean isActivated() {
14532        return (mPrivateFlags & ACTIVATED) != 0;
14533    }
14534
14535    /**
14536     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14537     * observer can be used to get notifications when global events, like
14538     * layout, happen.
14539     *
14540     * The returned ViewTreeObserver observer is not guaranteed to remain
14541     * valid for the lifetime of this View. If the caller of this method keeps
14542     * a long-lived reference to ViewTreeObserver, it should always check for
14543     * the return value of {@link ViewTreeObserver#isAlive()}.
14544     *
14545     * @return The ViewTreeObserver for this view's hierarchy.
14546     */
14547    public ViewTreeObserver getViewTreeObserver() {
14548        if (mAttachInfo != null) {
14549            return mAttachInfo.mTreeObserver;
14550        }
14551        if (mFloatingTreeObserver == null) {
14552            mFloatingTreeObserver = new ViewTreeObserver();
14553        }
14554        return mFloatingTreeObserver;
14555    }
14556
14557    /**
14558     * <p>Finds the topmost view in the current view hierarchy.</p>
14559     *
14560     * @return the topmost view containing this view
14561     */
14562    public View getRootView() {
14563        if (mAttachInfo != null) {
14564            final View v = mAttachInfo.mRootView;
14565            if (v != null) {
14566                return v;
14567            }
14568        }
14569
14570        View parent = this;
14571
14572        while (parent.mParent != null && parent.mParent instanceof View) {
14573            parent = (View) parent.mParent;
14574        }
14575
14576        return parent;
14577    }
14578
14579    /**
14580     * <p>Computes the coordinates of this view on the screen. The argument
14581     * must be an array of two integers. After the method returns, the array
14582     * contains the x and y location in that order.</p>
14583     *
14584     * @param location an array of two integers in which to hold the coordinates
14585     */
14586    public void getLocationOnScreen(int[] location) {
14587        getLocationInWindow(location);
14588
14589        final AttachInfo info = mAttachInfo;
14590        if (info != null) {
14591            location[0] += info.mWindowLeft;
14592            location[1] += info.mWindowTop;
14593        }
14594    }
14595
14596    /**
14597     * <p>Computes the coordinates of this view in its window. The argument
14598     * must be an array of two integers. After the method returns, the array
14599     * contains the x and y location in that order.</p>
14600     *
14601     * @param location an array of two integers in which to hold the coordinates
14602     */
14603    public void getLocationInWindow(int[] location) {
14604        if (location == null || location.length < 2) {
14605            throw new IllegalArgumentException("location must be an array of two integers");
14606        }
14607
14608        if (mAttachInfo == null) {
14609            // When the view is not attached to a window, this method does not make sense
14610            location[0] = location[1] = 0;
14611            return;
14612        }
14613
14614        float[] position = mAttachInfo.mTmpTransformLocation;
14615        position[0] = position[1] = 0.0f;
14616
14617        if (!hasIdentityMatrix()) {
14618            getMatrix().mapPoints(position);
14619        }
14620
14621        position[0] += mLeft;
14622        position[1] += mTop;
14623
14624        ViewParent viewParent = mParent;
14625        while (viewParent instanceof View) {
14626            final View view = (View) viewParent;
14627
14628            position[0] -= view.mScrollX;
14629            position[1] -= view.mScrollY;
14630
14631            if (!view.hasIdentityMatrix()) {
14632                view.getMatrix().mapPoints(position);
14633            }
14634
14635            position[0] += view.mLeft;
14636            position[1] += view.mTop;
14637
14638            viewParent = view.mParent;
14639         }
14640
14641        if (viewParent instanceof ViewRootImpl) {
14642            // *cough*
14643            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14644            position[1] -= vr.mCurScrollY;
14645        }
14646
14647        location[0] = (int) (position[0] + 0.5f);
14648        location[1] = (int) (position[1] + 0.5f);
14649    }
14650
14651    /**
14652     * {@hide}
14653     * @param id the id of the view to be found
14654     * @return the view of the specified id, null if cannot be found
14655     */
14656    protected View findViewTraversal(int id) {
14657        if (id == mID) {
14658            return this;
14659        }
14660        return null;
14661    }
14662
14663    /**
14664     * {@hide}
14665     * @param tag the tag of the view to be found
14666     * @return the view of specified tag, null if cannot be found
14667     */
14668    protected View findViewWithTagTraversal(Object tag) {
14669        if (tag != null && tag.equals(mTag)) {
14670            return this;
14671        }
14672        return null;
14673    }
14674
14675    /**
14676     * {@hide}
14677     * @param predicate The predicate to evaluate.
14678     * @param childToSkip If not null, ignores this child during the recursive traversal.
14679     * @return The first view that matches the predicate or null.
14680     */
14681    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14682        if (predicate.apply(this)) {
14683            return this;
14684        }
14685        return null;
14686    }
14687
14688    /**
14689     * Look for a child view with the given id.  If this view has the given
14690     * id, return this view.
14691     *
14692     * @param id The id to search for.
14693     * @return The view that has the given id in the hierarchy or null
14694     */
14695    public final View findViewById(int id) {
14696        if (id < 0) {
14697            return null;
14698        }
14699        return findViewTraversal(id);
14700    }
14701
14702    /**
14703     * Finds a view by its unuque and stable accessibility id.
14704     *
14705     * @param accessibilityId The searched accessibility id.
14706     * @return The found view.
14707     */
14708    final View findViewByAccessibilityId(int accessibilityId) {
14709        if (accessibilityId < 0) {
14710            return null;
14711        }
14712        return findViewByAccessibilityIdTraversal(accessibilityId);
14713    }
14714
14715    /**
14716     * Performs the traversal to find a view by its unuque and stable accessibility id.
14717     *
14718     * <strong>Note:</strong>This method does not stop at the root namespace
14719     * boundary since the user can touch the screen at an arbitrary location
14720     * potentially crossing the root namespace bounday which will send an
14721     * accessibility event to accessibility services and they should be able
14722     * to obtain the event source. Also accessibility ids are guaranteed to be
14723     * unique in the window.
14724     *
14725     * @param accessibilityId The accessibility id.
14726     * @return The found view.
14727     */
14728    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14729        if (getAccessibilityViewId() == accessibilityId) {
14730            return this;
14731        }
14732        return null;
14733    }
14734
14735    /**
14736     * Look for a child view with the given tag.  If this view has the given
14737     * tag, return this view.
14738     *
14739     * @param tag The tag to search for, using "tag.equals(getTag())".
14740     * @return The View that has the given tag in the hierarchy or null
14741     */
14742    public final View findViewWithTag(Object tag) {
14743        if (tag == null) {
14744            return null;
14745        }
14746        return findViewWithTagTraversal(tag);
14747    }
14748
14749    /**
14750     * {@hide}
14751     * Look for a child view that matches the specified predicate.
14752     * If this view matches the predicate, return this view.
14753     *
14754     * @param predicate The predicate to evaluate.
14755     * @return The first view that matches the predicate or null.
14756     */
14757    public final View findViewByPredicate(Predicate<View> predicate) {
14758        return findViewByPredicateTraversal(predicate, null);
14759    }
14760
14761    /**
14762     * {@hide}
14763     * Look for a child view that matches the specified predicate,
14764     * starting with the specified view and its descendents and then
14765     * recusively searching the ancestors and siblings of that view
14766     * until this view is reached.
14767     *
14768     * This method is useful in cases where the predicate does not match
14769     * a single unique view (perhaps multiple views use the same id)
14770     * and we are trying to find the view that is "closest" in scope to the
14771     * starting view.
14772     *
14773     * @param start The view to start from.
14774     * @param predicate The predicate to evaluate.
14775     * @return The first view that matches the predicate or null.
14776     */
14777    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14778        View childToSkip = null;
14779        for (;;) {
14780            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14781            if (view != null || start == this) {
14782                return view;
14783            }
14784
14785            ViewParent parent = start.getParent();
14786            if (parent == null || !(parent instanceof View)) {
14787                return null;
14788            }
14789
14790            childToSkip = start;
14791            start = (View) parent;
14792        }
14793    }
14794
14795    /**
14796     * Sets the identifier for this view. The identifier does not have to be
14797     * unique in this view's hierarchy. The identifier should be a positive
14798     * number.
14799     *
14800     * @see #NO_ID
14801     * @see #getId()
14802     * @see #findViewById(int)
14803     *
14804     * @param id a number used to identify the view
14805     *
14806     * @attr ref android.R.styleable#View_id
14807     */
14808    public void setId(int id) {
14809        mID = id;
14810    }
14811
14812    /**
14813     * {@hide}
14814     *
14815     * @param isRoot true if the view belongs to the root namespace, false
14816     *        otherwise
14817     */
14818    public void setIsRootNamespace(boolean isRoot) {
14819        if (isRoot) {
14820            mPrivateFlags |= IS_ROOT_NAMESPACE;
14821        } else {
14822            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14823        }
14824    }
14825
14826    /**
14827     * {@hide}
14828     *
14829     * @return true if the view belongs to the root namespace, false otherwise
14830     */
14831    public boolean isRootNamespace() {
14832        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14833    }
14834
14835    /**
14836     * Returns this view's identifier.
14837     *
14838     * @return a positive integer used to identify the view or {@link #NO_ID}
14839     *         if the view has no ID
14840     *
14841     * @see #setId(int)
14842     * @see #findViewById(int)
14843     * @attr ref android.R.styleable#View_id
14844     */
14845    @ViewDebug.CapturedViewProperty
14846    public int getId() {
14847        return mID;
14848    }
14849
14850    /**
14851     * Returns this view's tag.
14852     *
14853     * @return the Object stored in this view as a tag
14854     *
14855     * @see #setTag(Object)
14856     * @see #getTag(int)
14857     */
14858    @ViewDebug.ExportedProperty
14859    public Object getTag() {
14860        return mTag;
14861    }
14862
14863    /**
14864     * Sets the tag associated with this view. A tag can be used to mark
14865     * a view in its hierarchy and does not have to be unique within the
14866     * hierarchy. Tags can also be used to store data within a view without
14867     * resorting to another data structure.
14868     *
14869     * @param tag an Object to tag the view with
14870     *
14871     * @see #getTag()
14872     * @see #setTag(int, Object)
14873     */
14874    public void setTag(final Object tag) {
14875        mTag = tag;
14876    }
14877
14878    /**
14879     * Returns the tag associated with this view and the specified key.
14880     *
14881     * @param key The key identifying the tag
14882     *
14883     * @return the Object stored in this view as a tag
14884     *
14885     * @see #setTag(int, Object)
14886     * @see #getTag()
14887     */
14888    public Object getTag(int key) {
14889        if (mKeyedTags != null) return mKeyedTags.get(key);
14890        return null;
14891    }
14892
14893    /**
14894     * Sets a tag associated with this view and a key. A tag can be used
14895     * to mark a view in its hierarchy and does not have to be unique within
14896     * the hierarchy. Tags can also be used to store data within a view
14897     * without resorting to another data structure.
14898     *
14899     * The specified key should be an id declared in the resources of the
14900     * application to ensure it is unique (see the <a
14901     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14902     * Keys identified as belonging to
14903     * the Android framework or not associated with any package will cause
14904     * an {@link IllegalArgumentException} to be thrown.
14905     *
14906     * @param key The key identifying the tag
14907     * @param tag An Object to tag the view with
14908     *
14909     * @throws IllegalArgumentException If they specified key is not valid
14910     *
14911     * @see #setTag(Object)
14912     * @see #getTag(int)
14913     */
14914    public void setTag(int key, final Object tag) {
14915        // If the package id is 0x00 or 0x01, it's either an undefined package
14916        // or a framework id
14917        if ((key >>> 24) < 2) {
14918            throw new IllegalArgumentException("The key must be an application-specific "
14919                    + "resource id.");
14920        }
14921
14922        setKeyedTag(key, tag);
14923    }
14924
14925    /**
14926     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14927     * framework id.
14928     *
14929     * @hide
14930     */
14931    public void setTagInternal(int key, Object tag) {
14932        if ((key >>> 24) != 0x1) {
14933            throw new IllegalArgumentException("The key must be a framework-specific "
14934                    + "resource id.");
14935        }
14936
14937        setKeyedTag(key, tag);
14938    }
14939
14940    private void setKeyedTag(int key, Object tag) {
14941        if (mKeyedTags == null) {
14942            mKeyedTags = new SparseArray<Object>();
14943        }
14944
14945        mKeyedTags.put(key, tag);
14946    }
14947
14948    /**
14949     * Prints information about this view in the log output, with the tag
14950     * {@link #VIEW_LOG_TAG}.
14951     *
14952     * @hide
14953     */
14954    public void debug() {
14955        debug(0);
14956    }
14957
14958    /**
14959     * Prints information about this view in the log output, with the tag
14960     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14961     * indentation defined by the <code>depth</code>.
14962     *
14963     * @param depth the indentation level
14964     *
14965     * @hide
14966     */
14967    protected void debug(int depth) {
14968        String output = debugIndent(depth - 1);
14969
14970        output += "+ " + this;
14971        int id = getId();
14972        if (id != -1) {
14973            output += " (id=" + id + ")";
14974        }
14975        Object tag = getTag();
14976        if (tag != null) {
14977            output += " (tag=" + tag + ")";
14978        }
14979        Log.d(VIEW_LOG_TAG, output);
14980
14981        if ((mPrivateFlags & FOCUSED) != 0) {
14982            output = debugIndent(depth) + " FOCUSED";
14983            Log.d(VIEW_LOG_TAG, output);
14984        }
14985
14986        output = debugIndent(depth);
14987        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14988                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14989                + "} ";
14990        Log.d(VIEW_LOG_TAG, output);
14991
14992        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14993                || mPaddingBottom != 0) {
14994            output = debugIndent(depth);
14995            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14996                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14997            Log.d(VIEW_LOG_TAG, output);
14998        }
14999
15000        output = debugIndent(depth);
15001        output += "mMeasureWidth=" + mMeasuredWidth +
15002                " mMeasureHeight=" + mMeasuredHeight;
15003        Log.d(VIEW_LOG_TAG, output);
15004
15005        output = debugIndent(depth);
15006        if (mLayoutParams == null) {
15007            output += "BAD! no layout params";
15008        } else {
15009            output = mLayoutParams.debug(output);
15010        }
15011        Log.d(VIEW_LOG_TAG, output);
15012
15013        output = debugIndent(depth);
15014        output += "flags={";
15015        output += View.printFlags(mViewFlags);
15016        output += "}";
15017        Log.d(VIEW_LOG_TAG, output);
15018
15019        output = debugIndent(depth);
15020        output += "privateFlags={";
15021        output += View.printPrivateFlags(mPrivateFlags);
15022        output += "}";
15023        Log.d(VIEW_LOG_TAG, output);
15024    }
15025
15026    /**
15027     * Creates a string of whitespaces used for indentation.
15028     *
15029     * @param depth the indentation level
15030     * @return a String containing (depth * 2 + 3) * 2 white spaces
15031     *
15032     * @hide
15033     */
15034    protected static String debugIndent(int depth) {
15035        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15036        for (int i = 0; i < (depth * 2) + 3; i++) {
15037            spaces.append(' ').append(' ');
15038        }
15039        return spaces.toString();
15040    }
15041
15042    /**
15043     * <p>Return the offset of the widget's text baseline from the widget's top
15044     * boundary. If this widget does not support baseline alignment, this
15045     * method returns -1. </p>
15046     *
15047     * @return the offset of the baseline within the widget's bounds or -1
15048     *         if baseline alignment is not supported
15049     */
15050    @ViewDebug.ExportedProperty(category = "layout")
15051    public int getBaseline() {
15052        return -1;
15053    }
15054
15055    /**
15056     * Call this when something has changed which has invalidated the
15057     * layout of this view. This will schedule a layout pass of the view
15058     * tree.
15059     */
15060    public void requestLayout() {
15061        mPrivateFlags |= FORCE_LAYOUT;
15062        mPrivateFlags |= INVALIDATED;
15063
15064        if (mLayoutParams != null) {
15065            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
15066        }
15067
15068        if (mParent != null && !mParent.isLayoutRequested()) {
15069            mParent.requestLayout();
15070        }
15071    }
15072
15073    /**
15074     * Forces this view to be laid out during the next layout pass.
15075     * This method does not call requestLayout() or forceLayout()
15076     * on the parent.
15077     */
15078    public void forceLayout() {
15079        mPrivateFlags |= FORCE_LAYOUT;
15080        mPrivateFlags |= INVALIDATED;
15081    }
15082
15083    /**
15084     * <p>
15085     * This is called to find out how big a view should be. The parent
15086     * supplies constraint information in the width and height parameters.
15087     * </p>
15088     *
15089     * <p>
15090     * The actual measurement work of a view is performed in
15091     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15092     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15093     * </p>
15094     *
15095     *
15096     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15097     *        parent
15098     * @param heightMeasureSpec Vertical space requirements as imposed by the
15099     *        parent
15100     *
15101     * @see #onMeasure(int, int)
15102     */
15103    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15104        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
15105                widthMeasureSpec != mOldWidthMeasureSpec ||
15106                heightMeasureSpec != mOldHeightMeasureSpec) {
15107
15108            // first clears the measured dimension flag
15109            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
15110
15111            // measure ourselves, this should set the measured dimension flag back
15112            onMeasure(widthMeasureSpec, heightMeasureSpec);
15113
15114            // flag not set, setMeasuredDimension() was not invoked, we raise
15115            // an exception to warn the developer
15116            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
15117                throw new IllegalStateException("onMeasure() did not set the"
15118                        + " measured dimension by calling"
15119                        + " setMeasuredDimension()");
15120            }
15121
15122            mPrivateFlags |= LAYOUT_REQUIRED;
15123        }
15124
15125        mOldWidthMeasureSpec = widthMeasureSpec;
15126        mOldHeightMeasureSpec = heightMeasureSpec;
15127    }
15128
15129    /**
15130     * <p>
15131     * Measure the view and its content to determine the measured width and the
15132     * measured height. This method is invoked by {@link #measure(int, int)} and
15133     * should be overriden by subclasses to provide accurate and efficient
15134     * measurement of their contents.
15135     * </p>
15136     *
15137     * <p>
15138     * <strong>CONTRACT:</strong> When overriding this method, you
15139     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15140     * measured width and height of this view. Failure to do so will trigger an
15141     * <code>IllegalStateException</code>, thrown by
15142     * {@link #measure(int, int)}. Calling the superclass'
15143     * {@link #onMeasure(int, int)} is a valid use.
15144     * </p>
15145     *
15146     * <p>
15147     * The base class implementation of measure defaults to the background size,
15148     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15149     * override {@link #onMeasure(int, int)} to provide better measurements of
15150     * their content.
15151     * </p>
15152     *
15153     * <p>
15154     * If this method is overridden, it is the subclass's responsibility to make
15155     * sure the measured height and width are at least the view's minimum height
15156     * and width ({@link #getSuggestedMinimumHeight()} and
15157     * {@link #getSuggestedMinimumWidth()}).
15158     * </p>
15159     *
15160     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15161     *                         The requirements are encoded with
15162     *                         {@link android.view.View.MeasureSpec}.
15163     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15164     *                         The requirements are encoded with
15165     *                         {@link android.view.View.MeasureSpec}.
15166     *
15167     * @see #getMeasuredWidth()
15168     * @see #getMeasuredHeight()
15169     * @see #setMeasuredDimension(int, int)
15170     * @see #getSuggestedMinimumHeight()
15171     * @see #getSuggestedMinimumWidth()
15172     * @see android.view.View.MeasureSpec#getMode(int)
15173     * @see android.view.View.MeasureSpec#getSize(int)
15174     */
15175    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15176        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15177                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15178    }
15179
15180    /**
15181     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15182     * measured width and measured height. Failing to do so will trigger an
15183     * exception at measurement time.</p>
15184     *
15185     * @param measuredWidth The measured width of this view.  May be a complex
15186     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15187     * {@link #MEASURED_STATE_TOO_SMALL}.
15188     * @param measuredHeight The measured height of this view.  May be a complex
15189     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15190     * {@link #MEASURED_STATE_TOO_SMALL}.
15191     */
15192    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15193        mMeasuredWidth = measuredWidth;
15194        mMeasuredHeight = measuredHeight;
15195
15196        mPrivateFlags |= MEASURED_DIMENSION_SET;
15197    }
15198
15199    /**
15200     * Merge two states as returned by {@link #getMeasuredState()}.
15201     * @param curState The current state as returned from a view or the result
15202     * of combining multiple views.
15203     * @param newState The new view state to combine.
15204     * @return Returns a new integer reflecting the combination of the two
15205     * states.
15206     */
15207    public static int combineMeasuredStates(int curState, int newState) {
15208        return curState | newState;
15209    }
15210
15211    /**
15212     * Version of {@link #resolveSizeAndState(int, int, int)}
15213     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15214     */
15215    public static int resolveSize(int size, int measureSpec) {
15216        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15217    }
15218
15219    /**
15220     * Utility to reconcile a desired size and state, with constraints imposed
15221     * by a MeasureSpec.  Will take the desired size, unless a different size
15222     * is imposed by the constraints.  The returned value is a compound integer,
15223     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15224     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15225     * size is smaller than the size the view wants to be.
15226     *
15227     * @param size How big the view wants to be
15228     * @param measureSpec Constraints imposed by the parent
15229     * @return Size information bit mask as defined by
15230     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15231     */
15232    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15233        int result = size;
15234        int specMode = MeasureSpec.getMode(measureSpec);
15235        int specSize =  MeasureSpec.getSize(measureSpec);
15236        switch (specMode) {
15237        case MeasureSpec.UNSPECIFIED:
15238            result = size;
15239            break;
15240        case MeasureSpec.AT_MOST:
15241            if (specSize < size) {
15242                result = specSize | MEASURED_STATE_TOO_SMALL;
15243            } else {
15244                result = size;
15245            }
15246            break;
15247        case MeasureSpec.EXACTLY:
15248            result = specSize;
15249            break;
15250        }
15251        return result | (childMeasuredState&MEASURED_STATE_MASK);
15252    }
15253
15254    /**
15255     * Utility to return a default size. Uses the supplied size if the
15256     * MeasureSpec imposed no constraints. Will get larger if allowed
15257     * by the MeasureSpec.
15258     *
15259     * @param size Default size for this view
15260     * @param measureSpec Constraints imposed by the parent
15261     * @return The size this view should be.
15262     */
15263    public static int getDefaultSize(int size, int measureSpec) {
15264        int result = size;
15265        int specMode = MeasureSpec.getMode(measureSpec);
15266        int specSize = MeasureSpec.getSize(measureSpec);
15267
15268        switch (specMode) {
15269        case MeasureSpec.UNSPECIFIED:
15270            result = size;
15271            break;
15272        case MeasureSpec.AT_MOST:
15273        case MeasureSpec.EXACTLY:
15274            result = specSize;
15275            break;
15276        }
15277        return result;
15278    }
15279
15280    /**
15281     * Returns the suggested minimum height that the view should use. This
15282     * returns the maximum of the view's minimum height
15283     * and the background's minimum height
15284     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15285     * <p>
15286     * When being used in {@link #onMeasure(int, int)}, the caller should still
15287     * ensure the returned height is within the requirements of the parent.
15288     *
15289     * @return The suggested minimum height of the view.
15290     */
15291    protected int getSuggestedMinimumHeight() {
15292        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15293
15294    }
15295
15296    /**
15297     * Returns the suggested minimum width that the view should use. This
15298     * returns the maximum of the view's minimum width)
15299     * and the background's minimum width
15300     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15301     * <p>
15302     * When being used in {@link #onMeasure(int, int)}, the caller should still
15303     * ensure the returned width is within the requirements of the parent.
15304     *
15305     * @return The suggested minimum width of the view.
15306     */
15307    protected int getSuggestedMinimumWidth() {
15308        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15309    }
15310
15311    /**
15312     * Returns the minimum height of the view.
15313     *
15314     * @return the minimum height the view will try to be.
15315     *
15316     * @see #setMinimumHeight(int)
15317     *
15318     * @attr ref android.R.styleable#View_minHeight
15319     */
15320    public int getMinimumHeight() {
15321        return mMinHeight;
15322    }
15323
15324    /**
15325     * Sets the minimum height of the view. It is not guaranteed the view will
15326     * be able to achieve this minimum height (for example, if its parent layout
15327     * constrains it with less available height).
15328     *
15329     * @param minHeight The minimum height the view will try to be.
15330     *
15331     * @see #getMinimumHeight()
15332     *
15333     * @attr ref android.R.styleable#View_minHeight
15334     */
15335    public void setMinimumHeight(int minHeight) {
15336        mMinHeight = minHeight;
15337        requestLayout();
15338    }
15339
15340    /**
15341     * Returns the minimum width of the view.
15342     *
15343     * @return the minimum width the view will try to be.
15344     *
15345     * @see #setMinimumWidth(int)
15346     *
15347     * @attr ref android.R.styleable#View_minWidth
15348     */
15349    public int getMinimumWidth() {
15350        return mMinWidth;
15351    }
15352
15353    /**
15354     * Sets the minimum width of the view. It is not guaranteed the view will
15355     * be able to achieve this minimum width (for example, if its parent layout
15356     * constrains it with less available width).
15357     *
15358     * @param minWidth The minimum width the view will try to be.
15359     *
15360     * @see #getMinimumWidth()
15361     *
15362     * @attr ref android.R.styleable#View_minWidth
15363     */
15364    public void setMinimumWidth(int minWidth) {
15365        mMinWidth = minWidth;
15366        requestLayout();
15367
15368    }
15369
15370    /**
15371     * Get the animation currently associated with this view.
15372     *
15373     * @return The animation that is currently playing or
15374     *         scheduled to play for this view.
15375     */
15376    public Animation getAnimation() {
15377        return mCurrentAnimation;
15378    }
15379
15380    /**
15381     * Start the specified animation now.
15382     *
15383     * @param animation the animation to start now
15384     */
15385    public void startAnimation(Animation animation) {
15386        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15387        setAnimation(animation);
15388        invalidateParentCaches();
15389        invalidate(true);
15390    }
15391
15392    /**
15393     * Cancels any animations for this view.
15394     */
15395    public void clearAnimation() {
15396        if (mCurrentAnimation != null) {
15397            mCurrentAnimation.detach();
15398        }
15399        mCurrentAnimation = null;
15400        invalidateParentIfNeeded();
15401    }
15402
15403    /**
15404     * Sets the next animation to play for this view.
15405     * If you want the animation to play immediately, use
15406     * {@link #startAnimation(android.view.animation.Animation)} instead.
15407     * This method provides allows fine-grained
15408     * control over the start time and invalidation, but you
15409     * must make sure that 1) the animation has a start time set, and
15410     * 2) the view's parent (which controls animations on its children)
15411     * will be invalidated when the animation is supposed to
15412     * start.
15413     *
15414     * @param animation The next animation, or null.
15415     */
15416    public void setAnimation(Animation animation) {
15417        mCurrentAnimation = animation;
15418
15419        if (animation != null) {
15420            // If the screen is off assume the animation start time is now instead of
15421            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15422            // would cause the animation to start when the screen turns back on
15423            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15424                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15425                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15426            }
15427            animation.reset();
15428        }
15429    }
15430
15431    /**
15432     * Invoked by a parent ViewGroup to notify the start of the animation
15433     * currently associated with this view. If you override this method,
15434     * always call super.onAnimationStart();
15435     *
15436     * @see #setAnimation(android.view.animation.Animation)
15437     * @see #getAnimation()
15438     */
15439    protected void onAnimationStart() {
15440        mPrivateFlags |= ANIMATION_STARTED;
15441    }
15442
15443    /**
15444     * Invoked by a parent ViewGroup to notify the end of the animation
15445     * currently associated with this view. If you override this method,
15446     * always call super.onAnimationEnd();
15447     *
15448     * @see #setAnimation(android.view.animation.Animation)
15449     * @see #getAnimation()
15450     */
15451    protected void onAnimationEnd() {
15452        mPrivateFlags &= ~ANIMATION_STARTED;
15453    }
15454
15455    /**
15456     * Invoked if there is a Transform that involves alpha. Subclass that can
15457     * draw themselves with the specified alpha should return true, and then
15458     * respect that alpha when their onDraw() is called. If this returns false
15459     * then the view may be redirected to draw into an offscreen buffer to
15460     * fulfill the request, which will look fine, but may be slower than if the
15461     * subclass handles it internally. The default implementation returns false.
15462     *
15463     * @param alpha The alpha (0..255) to apply to the view's drawing
15464     * @return true if the view can draw with the specified alpha.
15465     */
15466    protected boolean onSetAlpha(int alpha) {
15467        return false;
15468    }
15469
15470    /**
15471     * This is used by the RootView to perform an optimization when
15472     * the view hierarchy contains one or several SurfaceView.
15473     * SurfaceView is always considered transparent, but its children are not,
15474     * therefore all View objects remove themselves from the global transparent
15475     * region (passed as a parameter to this function).
15476     *
15477     * @param region The transparent region for this ViewAncestor (window).
15478     *
15479     * @return Returns true if the effective visibility of the view at this
15480     * point is opaque, regardless of the transparent region; returns false
15481     * if it is possible for underlying windows to be seen behind the view.
15482     *
15483     * {@hide}
15484     */
15485    public boolean gatherTransparentRegion(Region region) {
15486        final AttachInfo attachInfo = mAttachInfo;
15487        if (region != null && attachInfo != null) {
15488            final int pflags = mPrivateFlags;
15489            if ((pflags & SKIP_DRAW) == 0) {
15490                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15491                // remove it from the transparent region.
15492                final int[] location = attachInfo.mTransparentLocation;
15493                getLocationInWindow(location);
15494                region.op(location[0], location[1], location[0] + mRight - mLeft,
15495                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15496            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15497                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15498                // exists, so we remove the background drawable's non-transparent
15499                // parts from this transparent region.
15500                applyDrawableToTransparentRegion(mBackground, region);
15501            }
15502        }
15503        return true;
15504    }
15505
15506    /**
15507     * Play a sound effect for this view.
15508     *
15509     * <p>The framework will play sound effects for some built in actions, such as
15510     * clicking, but you may wish to play these effects in your widget,
15511     * for instance, for internal navigation.
15512     *
15513     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15514     * {@link #isSoundEffectsEnabled()} is true.
15515     *
15516     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15517     */
15518    public void playSoundEffect(int soundConstant) {
15519        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15520            return;
15521        }
15522        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15523    }
15524
15525    /**
15526     * BZZZTT!!1!
15527     *
15528     * <p>Provide haptic feedback to the user for this view.
15529     *
15530     * <p>The framework will provide haptic feedback for some built in actions,
15531     * such as long presses, but you may wish to provide feedback for your
15532     * own widget.
15533     *
15534     * <p>The feedback will only be performed if
15535     * {@link #isHapticFeedbackEnabled()} is true.
15536     *
15537     * @param feedbackConstant One of the constants defined in
15538     * {@link HapticFeedbackConstants}
15539     */
15540    public boolean performHapticFeedback(int feedbackConstant) {
15541        return performHapticFeedback(feedbackConstant, 0);
15542    }
15543
15544    /**
15545     * BZZZTT!!1!
15546     *
15547     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15548     *
15549     * @param feedbackConstant One of the constants defined in
15550     * {@link HapticFeedbackConstants}
15551     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15552     */
15553    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15554        if (mAttachInfo == null) {
15555            return false;
15556        }
15557        //noinspection SimplifiableIfStatement
15558        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15559                && !isHapticFeedbackEnabled()) {
15560            return false;
15561        }
15562        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15563                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15564    }
15565
15566    /**
15567     * Request that the visibility of the status bar or other screen/window
15568     * decorations be changed.
15569     *
15570     * <p>This method is used to put the over device UI into temporary modes
15571     * where the user's attention is focused more on the application content,
15572     * by dimming or hiding surrounding system affordances.  This is typically
15573     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15574     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15575     * to be placed behind the action bar (and with these flags other system
15576     * affordances) so that smooth transitions between hiding and showing them
15577     * can be done.
15578     *
15579     * <p>Two representative examples of the use of system UI visibility is
15580     * implementing a content browsing application (like a magazine reader)
15581     * and a video playing application.
15582     *
15583     * <p>The first code shows a typical implementation of a View in a content
15584     * browsing application.  In this implementation, the application goes
15585     * into a content-oriented mode by hiding the status bar and action bar,
15586     * and putting the navigation elements into lights out mode.  The user can
15587     * then interact with content while in this mode.  Such an application should
15588     * provide an easy way for the user to toggle out of the mode (such as to
15589     * check information in the status bar or access notifications).  In the
15590     * implementation here, this is done simply by tapping on the content.
15591     *
15592     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15593     *      content}
15594     *
15595     * <p>This second code sample shows a typical implementation of a View
15596     * in a video playing application.  In this situation, while the video is
15597     * playing the application would like to go into a complete full-screen mode,
15598     * to use as much of the display as possible for the video.  When in this state
15599     * the user can not interact with the application; the system intercepts
15600     * touching on the screen to pop the UI out of full screen mode.  See
15601     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15602     *
15603     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15604     *      content}
15605     *
15606     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15607     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15608     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15609     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15610     */
15611    public void setSystemUiVisibility(int visibility) {
15612        if (visibility != mSystemUiVisibility) {
15613            mSystemUiVisibility = visibility;
15614            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15615                mParent.recomputeViewAttributes(this);
15616            }
15617        }
15618    }
15619
15620    /**
15621     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15622     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15623     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15624     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15625     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15626     */
15627    public int getSystemUiVisibility() {
15628        return mSystemUiVisibility;
15629    }
15630
15631    /**
15632     * Returns the current system UI visibility that is currently set for
15633     * the entire window.  This is the combination of the
15634     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15635     * views in the window.
15636     */
15637    public int getWindowSystemUiVisibility() {
15638        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15639    }
15640
15641    /**
15642     * Override to find out when the window's requested system UI visibility
15643     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15644     * This is different from the callbacks recieved through
15645     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15646     * in that this is only telling you about the local request of the window,
15647     * not the actual values applied by the system.
15648     */
15649    public void onWindowSystemUiVisibilityChanged(int visible) {
15650    }
15651
15652    /**
15653     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15654     * the view hierarchy.
15655     */
15656    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15657        onWindowSystemUiVisibilityChanged(visible);
15658    }
15659
15660    /**
15661     * Set a listener to receive callbacks when the visibility of the system bar changes.
15662     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15663     */
15664    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15665        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15666        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15667            mParent.recomputeViewAttributes(this);
15668        }
15669    }
15670
15671    /**
15672     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15673     * the view hierarchy.
15674     */
15675    public void dispatchSystemUiVisibilityChanged(int visibility) {
15676        ListenerInfo li = mListenerInfo;
15677        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15678            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15679                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15680        }
15681    }
15682
15683    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15684        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15685        if (val != mSystemUiVisibility) {
15686            setSystemUiVisibility(val);
15687            return true;
15688        }
15689        return false;
15690    }
15691
15692    /** @hide */
15693    public void setDisabledSystemUiVisibility(int flags) {
15694        if (mAttachInfo != null) {
15695            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15696                mAttachInfo.mDisabledSystemUiVisibility = flags;
15697                if (mParent != null) {
15698                    mParent.recomputeViewAttributes(this);
15699                }
15700            }
15701        }
15702    }
15703
15704    /**
15705     * Creates an image that the system displays during the drag and drop
15706     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15707     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15708     * appearance as the given View. The default also positions the center of the drag shadow
15709     * directly under the touch point. If no View is provided (the constructor with no parameters
15710     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15711     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15712     * default is an invisible drag shadow.
15713     * <p>
15714     * You are not required to use the View you provide to the constructor as the basis of the
15715     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15716     * anything you want as the drag shadow.
15717     * </p>
15718     * <p>
15719     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15720     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15721     *  size and position of the drag shadow. It uses this data to construct a
15722     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15723     *  so that your application can draw the shadow image in the Canvas.
15724     * </p>
15725     *
15726     * <div class="special reference">
15727     * <h3>Developer Guides</h3>
15728     * <p>For a guide to implementing drag and drop features, read the
15729     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15730     * </div>
15731     */
15732    public static class DragShadowBuilder {
15733        private final WeakReference<View> mView;
15734
15735        /**
15736         * Constructs a shadow image builder based on a View. By default, the resulting drag
15737         * shadow will have the same appearance and dimensions as the View, with the touch point
15738         * over the center of the View.
15739         * @param view A View. Any View in scope can be used.
15740         */
15741        public DragShadowBuilder(View view) {
15742            mView = new WeakReference<View>(view);
15743        }
15744
15745        /**
15746         * Construct a shadow builder object with no associated View.  This
15747         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15748         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15749         * to supply the drag shadow's dimensions and appearance without
15750         * reference to any View object. If they are not overridden, then the result is an
15751         * invisible drag shadow.
15752         */
15753        public DragShadowBuilder() {
15754            mView = new WeakReference<View>(null);
15755        }
15756
15757        /**
15758         * Returns the View object that had been passed to the
15759         * {@link #View.DragShadowBuilder(View)}
15760         * constructor.  If that View parameter was {@code null} or if the
15761         * {@link #View.DragShadowBuilder()}
15762         * constructor was used to instantiate the builder object, this method will return
15763         * null.
15764         *
15765         * @return The View object associate with this builder object.
15766         */
15767        @SuppressWarnings({"JavadocReference"})
15768        final public View getView() {
15769            return mView.get();
15770        }
15771
15772        /**
15773         * Provides the metrics for the shadow image. These include the dimensions of
15774         * the shadow image, and the point within that shadow that should
15775         * be centered under the touch location while dragging.
15776         * <p>
15777         * The default implementation sets the dimensions of the shadow to be the
15778         * same as the dimensions of the View itself and centers the shadow under
15779         * the touch point.
15780         * </p>
15781         *
15782         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15783         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15784         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15785         * image.
15786         *
15787         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15788         * shadow image that should be underneath the touch point during the drag and drop
15789         * operation. Your application must set {@link android.graphics.Point#x} to the
15790         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15791         */
15792        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15793            final View view = mView.get();
15794            if (view != null) {
15795                shadowSize.set(view.getWidth(), view.getHeight());
15796                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15797            } else {
15798                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15799            }
15800        }
15801
15802        /**
15803         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15804         * based on the dimensions it received from the
15805         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15806         *
15807         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15808         */
15809        public void onDrawShadow(Canvas canvas) {
15810            final View view = mView.get();
15811            if (view != null) {
15812                view.draw(canvas);
15813            } else {
15814                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15815            }
15816        }
15817    }
15818
15819    /**
15820     * Starts a drag and drop operation. When your application calls this method, it passes a
15821     * {@link android.view.View.DragShadowBuilder} object to the system. The
15822     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15823     * to get metrics for the drag shadow, and then calls the object's
15824     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15825     * <p>
15826     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15827     *  drag events to all the View objects in your application that are currently visible. It does
15828     *  this either by calling the View object's drag listener (an implementation of
15829     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15830     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15831     *  Both are passed a {@link android.view.DragEvent} object that has a
15832     *  {@link android.view.DragEvent#getAction()} value of
15833     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15834     * </p>
15835     * <p>
15836     * Your application can invoke startDrag() on any attached View object. The View object does not
15837     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15838     * be related to the View the user selected for dragging.
15839     * </p>
15840     * @param data A {@link android.content.ClipData} object pointing to the data to be
15841     * transferred by the drag and drop operation.
15842     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15843     * drag shadow.
15844     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15845     * drop operation. This Object is put into every DragEvent object sent by the system during the
15846     * current drag.
15847     * <p>
15848     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15849     * to the target Views. For example, it can contain flags that differentiate between a
15850     * a copy operation and a move operation.
15851     * </p>
15852     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15853     * so the parameter should be set to 0.
15854     * @return {@code true} if the method completes successfully, or
15855     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15856     * do a drag, and so no drag operation is in progress.
15857     */
15858    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15859            Object myLocalState, int flags) {
15860        if (ViewDebug.DEBUG_DRAG) {
15861            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15862        }
15863        boolean okay = false;
15864
15865        Point shadowSize = new Point();
15866        Point shadowTouchPoint = new Point();
15867        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15868
15869        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15870                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15871            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15872        }
15873
15874        if (ViewDebug.DEBUG_DRAG) {
15875            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15876                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15877        }
15878        Surface surface = new Surface();
15879        try {
15880            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15881                    flags, shadowSize.x, shadowSize.y, surface);
15882            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15883                    + " surface=" + surface);
15884            if (token != null) {
15885                Canvas canvas = surface.lockCanvas(null);
15886                try {
15887                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15888                    shadowBuilder.onDrawShadow(canvas);
15889                } finally {
15890                    surface.unlockCanvasAndPost(canvas);
15891                }
15892
15893                final ViewRootImpl root = getViewRootImpl();
15894
15895                // Cache the local state object for delivery with DragEvents
15896                root.setLocalDragState(myLocalState);
15897
15898                // repurpose 'shadowSize' for the last touch point
15899                root.getLastTouchPoint(shadowSize);
15900
15901                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15902                        shadowSize.x, shadowSize.y,
15903                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15904                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15905
15906                // Off and running!  Release our local surface instance; the drag
15907                // shadow surface is now managed by the system process.
15908                surface.release();
15909            }
15910        } catch (Exception e) {
15911            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15912            surface.destroy();
15913        }
15914
15915        return okay;
15916    }
15917
15918    /**
15919     * Handles drag events sent by the system following a call to
15920     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15921     *<p>
15922     * When the system calls this method, it passes a
15923     * {@link android.view.DragEvent} object. A call to
15924     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15925     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15926     * operation.
15927     * @param event The {@link android.view.DragEvent} sent by the system.
15928     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15929     * in DragEvent, indicating the type of drag event represented by this object.
15930     * @return {@code true} if the method was successful, otherwise {@code false}.
15931     * <p>
15932     *  The method should return {@code true} in response to an action type of
15933     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15934     *  operation.
15935     * </p>
15936     * <p>
15937     *  The method should also return {@code true} in response to an action type of
15938     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15939     *  {@code false} if it didn't.
15940     * </p>
15941     */
15942    public boolean onDragEvent(DragEvent event) {
15943        return false;
15944    }
15945
15946    /**
15947     * Detects if this View is enabled and has a drag event listener.
15948     * If both are true, then it calls the drag event listener with the
15949     * {@link android.view.DragEvent} it received. If the drag event listener returns
15950     * {@code true}, then dispatchDragEvent() returns {@code true}.
15951     * <p>
15952     * For all other cases, the method calls the
15953     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15954     * method and returns its result.
15955     * </p>
15956     * <p>
15957     * This ensures that a drag event is always consumed, even if the View does not have a drag
15958     * event listener. However, if the View has a listener and the listener returns true, then
15959     * onDragEvent() is not called.
15960     * </p>
15961     */
15962    public boolean dispatchDragEvent(DragEvent event) {
15963        //noinspection SimplifiableIfStatement
15964        ListenerInfo li = mListenerInfo;
15965        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15966                && li.mOnDragListener.onDrag(this, event)) {
15967            return true;
15968        }
15969        return onDragEvent(event);
15970    }
15971
15972    boolean canAcceptDrag() {
15973        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15974    }
15975
15976    /**
15977     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15978     * it is ever exposed at all.
15979     * @hide
15980     */
15981    public void onCloseSystemDialogs(String reason) {
15982    }
15983
15984    /**
15985     * Given a Drawable whose bounds have been set to draw into this view,
15986     * update a Region being computed for
15987     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15988     * that any non-transparent parts of the Drawable are removed from the
15989     * given transparent region.
15990     *
15991     * @param dr The Drawable whose transparency is to be applied to the region.
15992     * @param region A Region holding the current transparency information,
15993     * where any parts of the region that are set are considered to be
15994     * transparent.  On return, this region will be modified to have the
15995     * transparency information reduced by the corresponding parts of the
15996     * Drawable that are not transparent.
15997     * {@hide}
15998     */
15999    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16000        if (DBG) {
16001            Log.i("View", "Getting transparent region for: " + this);
16002        }
16003        final Region r = dr.getTransparentRegion();
16004        final Rect db = dr.getBounds();
16005        final AttachInfo attachInfo = mAttachInfo;
16006        if (r != null && attachInfo != null) {
16007            final int w = getRight()-getLeft();
16008            final int h = getBottom()-getTop();
16009            if (db.left > 0) {
16010                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16011                r.op(0, 0, db.left, h, Region.Op.UNION);
16012            }
16013            if (db.right < w) {
16014                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16015                r.op(db.right, 0, w, h, Region.Op.UNION);
16016            }
16017            if (db.top > 0) {
16018                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16019                r.op(0, 0, w, db.top, Region.Op.UNION);
16020            }
16021            if (db.bottom < h) {
16022                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16023                r.op(0, db.bottom, w, h, Region.Op.UNION);
16024            }
16025            final int[] location = attachInfo.mTransparentLocation;
16026            getLocationInWindow(location);
16027            r.translate(location[0], location[1]);
16028            region.op(r, Region.Op.INTERSECT);
16029        } else {
16030            region.op(db, Region.Op.DIFFERENCE);
16031        }
16032    }
16033
16034    private void checkForLongClick(int delayOffset) {
16035        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16036            mHasPerformedLongPress = false;
16037
16038            if (mPendingCheckForLongPress == null) {
16039                mPendingCheckForLongPress = new CheckForLongPress();
16040            }
16041            mPendingCheckForLongPress.rememberWindowAttachCount();
16042            postDelayed(mPendingCheckForLongPress,
16043                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16044        }
16045    }
16046
16047    /**
16048     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16049     * LayoutInflater} class, which provides a full range of options for view inflation.
16050     *
16051     * @param context The Context object for your activity or application.
16052     * @param resource The resource ID to inflate
16053     * @param root A view group that will be the parent.  Used to properly inflate the
16054     * layout_* parameters.
16055     * @see LayoutInflater
16056     */
16057    public static View inflate(Context context, int resource, ViewGroup root) {
16058        LayoutInflater factory = LayoutInflater.from(context);
16059        return factory.inflate(resource, root);
16060    }
16061
16062    /**
16063     * Scroll the view with standard behavior for scrolling beyond the normal
16064     * content boundaries. Views that call this method should override
16065     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16066     * results of an over-scroll operation.
16067     *
16068     * Views can use this method to handle any touch or fling-based scrolling.
16069     *
16070     * @param deltaX Change in X in pixels
16071     * @param deltaY Change in Y in pixels
16072     * @param scrollX Current X scroll value in pixels before applying deltaX
16073     * @param scrollY Current Y scroll value in pixels before applying deltaY
16074     * @param scrollRangeX Maximum content scroll range along the X axis
16075     * @param scrollRangeY Maximum content scroll range along the Y axis
16076     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16077     *          along the X axis.
16078     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16079     *          along the Y axis.
16080     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16081     * @return true if scrolling was clamped to an over-scroll boundary along either
16082     *          axis, false otherwise.
16083     */
16084    @SuppressWarnings({"UnusedParameters"})
16085    protected boolean overScrollBy(int deltaX, int deltaY,
16086            int scrollX, int scrollY,
16087            int scrollRangeX, int scrollRangeY,
16088            int maxOverScrollX, int maxOverScrollY,
16089            boolean isTouchEvent) {
16090        final int overScrollMode = mOverScrollMode;
16091        final boolean canScrollHorizontal =
16092                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16093        final boolean canScrollVertical =
16094                computeVerticalScrollRange() > computeVerticalScrollExtent();
16095        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16096                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16097        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16098                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16099
16100        int newScrollX = scrollX + deltaX;
16101        if (!overScrollHorizontal) {
16102            maxOverScrollX = 0;
16103        }
16104
16105        int newScrollY = scrollY + deltaY;
16106        if (!overScrollVertical) {
16107            maxOverScrollY = 0;
16108        }
16109
16110        // Clamp values if at the limits and record
16111        final int left = -maxOverScrollX;
16112        final int right = maxOverScrollX + scrollRangeX;
16113        final int top = -maxOverScrollY;
16114        final int bottom = maxOverScrollY + scrollRangeY;
16115
16116        boolean clampedX = false;
16117        if (newScrollX > right) {
16118            newScrollX = right;
16119            clampedX = true;
16120        } else if (newScrollX < left) {
16121            newScrollX = left;
16122            clampedX = true;
16123        }
16124
16125        boolean clampedY = false;
16126        if (newScrollY > bottom) {
16127            newScrollY = bottom;
16128            clampedY = true;
16129        } else if (newScrollY < top) {
16130            newScrollY = top;
16131            clampedY = true;
16132        }
16133
16134        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16135
16136        return clampedX || clampedY;
16137    }
16138
16139    /**
16140     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16141     * respond to the results of an over-scroll operation.
16142     *
16143     * @param scrollX New X scroll value in pixels
16144     * @param scrollY New Y scroll value in pixels
16145     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16146     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16147     */
16148    protected void onOverScrolled(int scrollX, int scrollY,
16149            boolean clampedX, boolean clampedY) {
16150        // Intentionally empty.
16151    }
16152
16153    /**
16154     * Returns the over-scroll mode for this view. The result will be
16155     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16156     * (allow over-scrolling only if the view content is larger than the container),
16157     * or {@link #OVER_SCROLL_NEVER}.
16158     *
16159     * @return This view's over-scroll mode.
16160     */
16161    public int getOverScrollMode() {
16162        return mOverScrollMode;
16163    }
16164
16165    /**
16166     * Set the over-scroll mode for this view. Valid over-scroll modes are
16167     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16168     * (allow over-scrolling only if the view content is larger than the container),
16169     * or {@link #OVER_SCROLL_NEVER}.
16170     *
16171     * Setting the over-scroll mode of a view will have an effect only if the
16172     * view is capable of scrolling.
16173     *
16174     * @param overScrollMode The new over-scroll mode for this view.
16175     */
16176    public void setOverScrollMode(int overScrollMode) {
16177        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16178                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16179                overScrollMode != OVER_SCROLL_NEVER) {
16180            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16181        }
16182        mOverScrollMode = overScrollMode;
16183    }
16184
16185    /**
16186     * Gets a scale factor that determines the distance the view should scroll
16187     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16188     * @return The vertical scroll scale factor.
16189     * @hide
16190     */
16191    protected float getVerticalScrollFactor() {
16192        if (mVerticalScrollFactor == 0) {
16193            TypedValue outValue = new TypedValue();
16194            if (!mContext.getTheme().resolveAttribute(
16195                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16196                throw new IllegalStateException(
16197                        "Expected theme to define listPreferredItemHeight.");
16198            }
16199            mVerticalScrollFactor = outValue.getDimension(
16200                    mContext.getResources().getDisplayMetrics());
16201        }
16202        return mVerticalScrollFactor;
16203    }
16204
16205    /**
16206     * Gets a scale factor that determines the distance the view should scroll
16207     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16208     * @return The horizontal scroll scale factor.
16209     * @hide
16210     */
16211    protected float getHorizontalScrollFactor() {
16212        // TODO: Should use something else.
16213        return getVerticalScrollFactor();
16214    }
16215
16216    /**
16217     * Return the value specifying the text direction or policy that was set with
16218     * {@link #setTextDirection(int)}.
16219     *
16220     * @return the defined text direction. It can be one of:
16221     *
16222     * {@link #TEXT_DIRECTION_INHERIT},
16223     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16224     * {@link #TEXT_DIRECTION_ANY_RTL},
16225     * {@link #TEXT_DIRECTION_LTR},
16226     * {@link #TEXT_DIRECTION_RTL},
16227     * {@link #TEXT_DIRECTION_LOCALE}
16228     * @hide
16229     */
16230    @ViewDebug.ExportedProperty(category = "text", mapping = {
16231            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16232            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16233            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16234            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16235            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16236            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16237    })
16238    public int getTextDirection() {
16239        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16240    }
16241
16242    /**
16243     * Set the text direction.
16244     *
16245     * @param textDirection the direction to set. Should be one of:
16246     *
16247     * {@link #TEXT_DIRECTION_INHERIT},
16248     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16249     * {@link #TEXT_DIRECTION_ANY_RTL},
16250     * {@link #TEXT_DIRECTION_LTR},
16251     * {@link #TEXT_DIRECTION_RTL},
16252     * {@link #TEXT_DIRECTION_LOCALE}
16253     * @hide
16254     */
16255    public void setTextDirection(int textDirection) {
16256        if (getTextDirection() != textDirection) {
16257            // Reset the current text direction and the resolved one
16258            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16259            resetResolvedTextDirection();
16260            // Set the new text direction
16261            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16262            // Refresh
16263            requestLayout();
16264            invalidate(true);
16265        }
16266    }
16267
16268    /**
16269     * Return the resolved text direction.
16270     *
16271     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16272     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16273     * up the parent chain of the view. if there is no parent, then it will return the default
16274     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16275     *
16276     * @return the resolved text direction. Returns one of:
16277     *
16278     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16279     * {@link #TEXT_DIRECTION_ANY_RTL},
16280     * {@link #TEXT_DIRECTION_LTR},
16281     * {@link #TEXT_DIRECTION_RTL},
16282     * {@link #TEXT_DIRECTION_LOCALE}
16283     * @hide
16284     */
16285    public int getResolvedTextDirection() {
16286        // The text direction will be resolved only if needed
16287        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16288            resolveTextDirection();
16289        }
16290        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16291    }
16292
16293    /**
16294     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16295     * resolution is done.
16296     * @hide
16297     */
16298    public void resolveTextDirection() {
16299        // Reset any previous text direction resolution
16300        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16301
16302        if (hasRtlSupport()) {
16303            // Set resolved text direction flag depending on text direction flag
16304            final int textDirection = getTextDirection();
16305            switch(textDirection) {
16306                case TEXT_DIRECTION_INHERIT:
16307                    if (canResolveTextDirection()) {
16308                        ViewGroup viewGroup = ((ViewGroup) mParent);
16309
16310                        // Set current resolved direction to the same value as the parent's one
16311                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16312                        switch (parentResolvedDirection) {
16313                            case TEXT_DIRECTION_FIRST_STRONG:
16314                            case TEXT_DIRECTION_ANY_RTL:
16315                            case TEXT_DIRECTION_LTR:
16316                            case TEXT_DIRECTION_RTL:
16317                            case TEXT_DIRECTION_LOCALE:
16318                                mPrivateFlags2 |=
16319                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16320                                break;
16321                            default:
16322                                // Default resolved direction is "first strong" heuristic
16323                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16324                        }
16325                    } else {
16326                        // We cannot do the resolution if there is no parent, so use the default one
16327                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16328                    }
16329                    break;
16330                case TEXT_DIRECTION_FIRST_STRONG:
16331                case TEXT_DIRECTION_ANY_RTL:
16332                case TEXT_DIRECTION_LTR:
16333                case TEXT_DIRECTION_RTL:
16334                case TEXT_DIRECTION_LOCALE:
16335                    // Resolved direction is the same as text direction
16336                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16337                    break;
16338                default:
16339                    // Default resolved direction is "first strong" heuristic
16340                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16341            }
16342        } else {
16343            // Default resolved direction is "first strong" heuristic
16344            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16345        }
16346
16347        // Set to resolved
16348        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16349        onResolvedTextDirectionChanged();
16350    }
16351
16352    /**
16353     * Called when text direction has been resolved. Subclasses that care about text direction
16354     * resolution should override this method.
16355     *
16356     * The default implementation does nothing.
16357     * @hide
16358     */
16359    public void onResolvedTextDirectionChanged() {
16360    }
16361
16362    /**
16363     * Check if text direction resolution can be done.
16364     *
16365     * @return true if text direction resolution can be done otherwise return false.
16366     * @hide
16367     */
16368    public boolean canResolveTextDirection() {
16369        switch (getTextDirection()) {
16370            case TEXT_DIRECTION_INHERIT:
16371                return (mParent != null) && (mParent instanceof ViewGroup);
16372            default:
16373                return true;
16374        }
16375    }
16376
16377    /**
16378     * Reset resolved text direction. Text direction can be resolved with a call to
16379     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16380     * reset is done.
16381     * @hide
16382     */
16383    public void resetResolvedTextDirection() {
16384        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16385        onResolvedTextDirectionReset();
16386    }
16387
16388    /**
16389     * Called when text direction is reset. Subclasses that care about text direction reset should
16390     * override this method and do a reset of the text direction of their children. The default
16391     * implementation does nothing.
16392     * @hide
16393     */
16394    public void onResolvedTextDirectionReset() {
16395    }
16396
16397    /**
16398     * Return the value specifying the text alignment or policy that was set with
16399     * {@link #setTextAlignment(int)}.
16400     *
16401     * @return the defined text alignment. It can be one of:
16402     *
16403     * {@link #TEXT_ALIGNMENT_INHERIT},
16404     * {@link #TEXT_ALIGNMENT_GRAVITY},
16405     * {@link #TEXT_ALIGNMENT_CENTER},
16406     * {@link #TEXT_ALIGNMENT_TEXT_START},
16407     * {@link #TEXT_ALIGNMENT_TEXT_END},
16408     * {@link #TEXT_ALIGNMENT_VIEW_START},
16409     * {@link #TEXT_ALIGNMENT_VIEW_END}
16410     * @hide
16411     */
16412    @ViewDebug.ExportedProperty(category = "text", mapping = {
16413            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16414            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16415            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16416            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16417            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16418            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16419            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16420    })
16421    public int getTextAlignment() {
16422        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16423    }
16424
16425    /**
16426     * Set the text alignment.
16427     *
16428     * @param textAlignment The text alignment to set. Should be one of
16429     *
16430     * {@link #TEXT_ALIGNMENT_INHERIT},
16431     * {@link #TEXT_ALIGNMENT_GRAVITY},
16432     * {@link #TEXT_ALIGNMENT_CENTER},
16433     * {@link #TEXT_ALIGNMENT_TEXT_START},
16434     * {@link #TEXT_ALIGNMENT_TEXT_END},
16435     * {@link #TEXT_ALIGNMENT_VIEW_START},
16436     * {@link #TEXT_ALIGNMENT_VIEW_END}
16437     *
16438     * @attr ref android.R.styleable#View_textAlignment
16439     * @hide
16440     */
16441    public void setTextAlignment(int textAlignment) {
16442        if (textAlignment != getTextAlignment()) {
16443            // Reset the current and resolved text alignment
16444            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16445            resetResolvedTextAlignment();
16446            // Set the new text alignment
16447            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16448            // Refresh
16449            requestLayout();
16450            invalidate(true);
16451        }
16452    }
16453
16454    /**
16455     * Return the resolved text alignment.
16456     *
16457     * The resolved text alignment. This needs resolution if the value is
16458     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16459     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16460     *
16461     * @return the resolved text alignment. Returns one of:
16462     *
16463     * {@link #TEXT_ALIGNMENT_GRAVITY},
16464     * {@link #TEXT_ALIGNMENT_CENTER},
16465     * {@link #TEXT_ALIGNMENT_TEXT_START},
16466     * {@link #TEXT_ALIGNMENT_TEXT_END},
16467     * {@link #TEXT_ALIGNMENT_VIEW_START},
16468     * {@link #TEXT_ALIGNMENT_VIEW_END}
16469     * @hide
16470     */
16471    @ViewDebug.ExportedProperty(category = "text", mapping = {
16472            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16473            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16474            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16475            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16476            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16477            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16478            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16479    })
16480    public int getResolvedTextAlignment() {
16481        // If text alignment is not resolved, then resolve it
16482        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16483            resolveTextAlignment();
16484        }
16485        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16486    }
16487
16488    /**
16489     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16490     * resolution is done.
16491     * @hide
16492     */
16493    public void resolveTextAlignment() {
16494        // Reset any previous text alignment resolution
16495        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16496
16497        if (hasRtlSupport()) {
16498            // Set resolved text alignment flag depending on text alignment flag
16499            final int textAlignment = getTextAlignment();
16500            switch (textAlignment) {
16501                case TEXT_ALIGNMENT_INHERIT:
16502                    // Check if we can resolve the text alignment
16503                    if (canResolveLayoutDirection() && mParent instanceof View) {
16504                        View view = (View) mParent;
16505
16506                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16507                        switch (parentResolvedTextAlignment) {
16508                            case TEXT_ALIGNMENT_GRAVITY:
16509                            case TEXT_ALIGNMENT_TEXT_START:
16510                            case TEXT_ALIGNMENT_TEXT_END:
16511                            case TEXT_ALIGNMENT_CENTER:
16512                            case TEXT_ALIGNMENT_VIEW_START:
16513                            case TEXT_ALIGNMENT_VIEW_END:
16514                                // Resolved text alignment is the same as the parent resolved
16515                                // text alignment
16516                                mPrivateFlags2 |=
16517                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16518                                break;
16519                            default:
16520                                // Use default resolved text alignment
16521                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16522                        }
16523                    }
16524                    else {
16525                        // We cannot do the resolution if there is no parent so use the default
16526                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16527                    }
16528                    break;
16529                case TEXT_ALIGNMENT_GRAVITY:
16530                case TEXT_ALIGNMENT_TEXT_START:
16531                case TEXT_ALIGNMENT_TEXT_END:
16532                case TEXT_ALIGNMENT_CENTER:
16533                case TEXT_ALIGNMENT_VIEW_START:
16534                case TEXT_ALIGNMENT_VIEW_END:
16535                    // Resolved text alignment is the same as text alignment
16536                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16537                    break;
16538                default:
16539                    // Use default resolved text alignment
16540                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16541            }
16542        } else {
16543            // Use default resolved text alignment
16544            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16545        }
16546
16547        // Set the resolved
16548        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16549        onResolvedTextAlignmentChanged();
16550    }
16551
16552    /**
16553     * Check if text alignment resolution can be done.
16554     *
16555     * @return true if text alignment resolution can be done otherwise return false.
16556     * @hide
16557     */
16558    public boolean canResolveTextAlignment() {
16559        switch (getTextAlignment()) {
16560            case TEXT_DIRECTION_INHERIT:
16561                return (mParent != null);
16562            default:
16563                return true;
16564        }
16565    }
16566
16567    /**
16568     * Called when text alignment has been resolved. Subclasses that care about text alignment
16569     * resolution should override this method.
16570     *
16571     * The default implementation does nothing.
16572     * @hide
16573     */
16574    public void onResolvedTextAlignmentChanged() {
16575    }
16576
16577    /**
16578     * Reset resolved text alignment. Text alignment can be resolved with a call to
16579     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16580     * reset is done.
16581     * @hide
16582     */
16583    public void resetResolvedTextAlignment() {
16584        // Reset any previous text alignment resolution
16585        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16586        onResolvedTextAlignmentReset();
16587    }
16588
16589    /**
16590     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16591     * override this method and do a reset of the text alignment of their children. The default
16592     * implementation does nothing.
16593     * @hide
16594     */
16595    public void onResolvedTextAlignmentReset() {
16596    }
16597
16598    //
16599    // Properties
16600    //
16601    /**
16602     * A Property wrapper around the <code>alpha</code> functionality handled by the
16603     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16604     */
16605    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16606        @Override
16607        public void setValue(View object, float value) {
16608            object.setAlpha(value);
16609        }
16610
16611        @Override
16612        public Float get(View object) {
16613            return object.getAlpha();
16614        }
16615    };
16616
16617    /**
16618     * A Property wrapper around the <code>translationX</code> functionality handled by the
16619     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16620     */
16621    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16622        @Override
16623        public void setValue(View object, float value) {
16624            object.setTranslationX(value);
16625        }
16626
16627                @Override
16628        public Float get(View object) {
16629            return object.getTranslationX();
16630        }
16631    };
16632
16633    /**
16634     * A Property wrapper around the <code>translationY</code> functionality handled by the
16635     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16636     */
16637    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16638        @Override
16639        public void setValue(View object, float value) {
16640            object.setTranslationY(value);
16641        }
16642
16643        @Override
16644        public Float get(View object) {
16645            return object.getTranslationY();
16646        }
16647    };
16648
16649    /**
16650     * A Property wrapper around the <code>x</code> functionality handled by the
16651     * {@link View#setX(float)} and {@link View#getX()} methods.
16652     */
16653    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16654        @Override
16655        public void setValue(View object, float value) {
16656            object.setX(value);
16657        }
16658
16659        @Override
16660        public Float get(View object) {
16661            return object.getX();
16662        }
16663    };
16664
16665    /**
16666     * A Property wrapper around the <code>y</code> functionality handled by the
16667     * {@link View#setY(float)} and {@link View#getY()} methods.
16668     */
16669    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16670        @Override
16671        public void setValue(View object, float value) {
16672            object.setY(value);
16673        }
16674
16675        @Override
16676        public Float get(View object) {
16677            return object.getY();
16678        }
16679    };
16680
16681    /**
16682     * A Property wrapper around the <code>rotation</code> functionality handled by the
16683     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16684     */
16685    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16686        @Override
16687        public void setValue(View object, float value) {
16688            object.setRotation(value);
16689        }
16690
16691        @Override
16692        public Float get(View object) {
16693            return object.getRotation();
16694        }
16695    };
16696
16697    /**
16698     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16699     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16700     */
16701    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16702        @Override
16703        public void setValue(View object, float value) {
16704            object.setRotationX(value);
16705        }
16706
16707        @Override
16708        public Float get(View object) {
16709            return object.getRotationX();
16710        }
16711    };
16712
16713    /**
16714     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16715     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16716     */
16717    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16718        @Override
16719        public void setValue(View object, float value) {
16720            object.setRotationY(value);
16721        }
16722
16723        @Override
16724        public Float get(View object) {
16725            return object.getRotationY();
16726        }
16727    };
16728
16729    /**
16730     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16731     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16732     */
16733    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16734        @Override
16735        public void setValue(View object, float value) {
16736            object.setScaleX(value);
16737        }
16738
16739        @Override
16740        public Float get(View object) {
16741            return object.getScaleX();
16742        }
16743    };
16744
16745    /**
16746     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16747     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16748     */
16749    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16750        @Override
16751        public void setValue(View object, float value) {
16752            object.setScaleY(value);
16753        }
16754
16755        @Override
16756        public Float get(View object) {
16757            return object.getScaleY();
16758        }
16759    };
16760
16761    /**
16762     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16763     * Each MeasureSpec represents a requirement for either the width or the height.
16764     * A MeasureSpec is comprised of a size and a mode. There are three possible
16765     * modes:
16766     * <dl>
16767     * <dt>UNSPECIFIED</dt>
16768     * <dd>
16769     * The parent has not imposed any constraint on the child. It can be whatever size
16770     * it wants.
16771     * </dd>
16772     *
16773     * <dt>EXACTLY</dt>
16774     * <dd>
16775     * The parent has determined an exact size for the child. The child is going to be
16776     * given those bounds regardless of how big it wants to be.
16777     * </dd>
16778     *
16779     * <dt>AT_MOST</dt>
16780     * <dd>
16781     * The child can be as large as it wants up to the specified size.
16782     * </dd>
16783     * </dl>
16784     *
16785     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16786     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16787     */
16788    public static class MeasureSpec {
16789        private static final int MODE_SHIFT = 30;
16790        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16791
16792        /**
16793         * Measure specification mode: The parent has not imposed any constraint
16794         * on the child. It can be whatever size it wants.
16795         */
16796        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16797
16798        /**
16799         * Measure specification mode: The parent has determined an exact size
16800         * for the child. The child is going to be given those bounds regardless
16801         * of how big it wants to be.
16802         */
16803        public static final int EXACTLY     = 1 << MODE_SHIFT;
16804
16805        /**
16806         * Measure specification mode: The child can be as large as it wants up
16807         * to the specified size.
16808         */
16809        public static final int AT_MOST     = 2 << MODE_SHIFT;
16810
16811        /**
16812         * Creates a measure specification based on the supplied size and mode.
16813         *
16814         * The mode must always be one of the following:
16815         * <ul>
16816         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16817         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16818         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16819         * </ul>
16820         *
16821         * @param size the size of the measure specification
16822         * @param mode the mode of the measure specification
16823         * @return the measure specification based on size and mode
16824         */
16825        public static int makeMeasureSpec(int size, int mode) {
16826            return size + mode;
16827        }
16828
16829        /**
16830         * Extracts the mode from the supplied measure specification.
16831         *
16832         * @param measureSpec the measure specification to extract the mode from
16833         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16834         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16835         *         {@link android.view.View.MeasureSpec#EXACTLY}
16836         */
16837        public static int getMode(int measureSpec) {
16838            return (measureSpec & MODE_MASK);
16839        }
16840
16841        /**
16842         * Extracts the size from the supplied measure specification.
16843         *
16844         * @param measureSpec the measure specification to extract the size from
16845         * @return the size in pixels defined in the supplied measure specification
16846         */
16847        public static int getSize(int measureSpec) {
16848            return (measureSpec & ~MODE_MASK);
16849        }
16850
16851        /**
16852         * Returns a String representation of the specified measure
16853         * specification.
16854         *
16855         * @param measureSpec the measure specification to convert to a String
16856         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16857         */
16858        public static String toString(int measureSpec) {
16859            int mode = getMode(measureSpec);
16860            int size = getSize(measureSpec);
16861
16862            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16863
16864            if (mode == UNSPECIFIED)
16865                sb.append("UNSPECIFIED ");
16866            else if (mode == EXACTLY)
16867                sb.append("EXACTLY ");
16868            else if (mode == AT_MOST)
16869                sb.append("AT_MOST ");
16870            else
16871                sb.append(mode).append(" ");
16872
16873            sb.append(size);
16874            return sb.toString();
16875        }
16876    }
16877
16878    class CheckForLongPress implements Runnable {
16879
16880        private int mOriginalWindowAttachCount;
16881
16882        public void run() {
16883            if (isPressed() && (mParent != null)
16884                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16885                if (performLongClick()) {
16886                    mHasPerformedLongPress = true;
16887                }
16888            }
16889        }
16890
16891        public void rememberWindowAttachCount() {
16892            mOriginalWindowAttachCount = mWindowAttachCount;
16893        }
16894    }
16895
16896    private final class CheckForTap implements Runnable {
16897        public void run() {
16898            mPrivateFlags &= ~PREPRESSED;
16899            setPressed(true);
16900            checkForLongClick(ViewConfiguration.getTapTimeout());
16901        }
16902    }
16903
16904    private final class PerformClick implements Runnable {
16905        public void run() {
16906            performClick();
16907        }
16908    }
16909
16910    /** @hide */
16911    public void hackTurnOffWindowResizeAnim(boolean off) {
16912        mAttachInfo.mTurnOffWindowResizeAnim = off;
16913    }
16914
16915    /**
16916     * This method returns a ViewPropertyAnimator object, which can be used to animate
16917     * specific properties on this View.
16918     *
16919     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16920     */
16921    public ViewPropertyAnimator animate() {
16922        if (mAnimator == null) {
16923            mAnimator = new ViewPropertyAnimator(this);
16924        }
16925        return mAnimator;
16926    }
16927
16928    /**
16929     * Interface definition for a callback to be invoked when a hardware key event is
16930     * dispatched to this view. The callback will be invoked before the key event is
16931     * given to the view. This is only useful for hardware keyboards; a software input
16932     * method has no obligation to trigger this listener.
16933     */
16934    public interface OnKeyListener {
16935        /**
16936         * Called when a hardware key is dispatched to a view. This allows listeners to
16937         * get a chance to respond before the target view.
16938         * <p>Key presses in software keyboards will generally NOT trigger this method,
16939         * although some may elect to do so in some situations. Do not assume a
16940         * software input method has to be key-based; even if it is, it may use key presses
16941         * in a different way than you expect, so there is no way to reliably catch soft
16942         * input key presses.
16943         *
16944         * @param v The view the key has been dispatched to.
16945         * @param keyCode The code for the physical key that was pressed
16946         * @param event The KeyEvent object containing full information about
16947         *        the event.
16948         * @return True if the listener has consumed the event, false otherwise.
16949         */
16950        boolean onKey(View v, int keyCode, KeyEvent event);
16951    }
16952
16953    /**
16954     * Interface definition for a callback to be invoked when a touch event is
16955     * dispatched to this view. The callback will be invoked before the touch
16956     * event is given to the view.
16957     */
16958    public interface OnTouchListener {
16959        /**
16960         * Called when a touch event is dispatched to a view. This allows listeners to
16961         * get a chance to respond before the target view.
16962         *
16963         * @param v The view the touch event has been dispatched to.
16964         * @param event The MotionEvent object containing full information about
16965         *        the event.
16966         * @return True if the listener has consumed the event, false otherwise.
16967         */
16968        boolean onTouch(View v, MotionEvent event);
16969    }
16970
16971    /**
16972     * Interface definition for a callback to be invoked when a hover event is
16973     * dispatched to this view. The callback will be invoked before the hover
16974     * event is given to the view.
16975     */
16976    public interface OnHoverListener {
16977        /**
16978         * Called when a hover event is dispatched to a view. This allows listeners to
16979         * get a chance to respond before the target view.
16980         *
16981         * @param v The view the hover event has been dispatched to.
16982         * @param event The MotionEvent object containing full information about
16983         *        the event.
16984         * @return True if the listener has consumed the event, false otherwise.
16985         */
16986        boolean onHover(View v, MotionEvent event);
16987    }
16988
16989    /**
16990     * Interface definition for a callback to be invoked when a generic motion event is
16991     * dispatched to this view. The callback will be invoked before the generic motion
16992     * event is given to the view.
16993     */
16994    public interface OnGenericMotionListener {
16995        /**
16996         * Called when a generic motion event is dispatched to a view. This allows listeners to
16997         * get a chance to respond before the target view.
16998         *
16999         * @param v The view the generic motion event has been dispatched to.
17000         * @param event The MotionEvent object containing full information about
17001         *        the event.
17002         * @return True if the listener has consumed the event, false otherwise.
17003         */
17004        boolean onGenericMotion(View v, MotionEvent event);
17005    }
17006
17007    /**
17008     * Interface definition for a callback to be invoked when a view has been clicked and held.
17009     */
17010    public interface OnLongClickListener {
17011        /**
17012         * Called when a view has been clicked and held.
17013         *
17014         * @param v The view that was clicked and held.
17015         *
17016         * @return true if the callback consumed the long click, false otherwise.
17017         */
17018        boolean onLongClick(View v);
17019    }
17020
17021    /**
17022     * Interface definition for a callback to be invoked when a drag is being dispatched
17023     * to this view.  The callback will be invoked before the hosting view's own
17024     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17025     * onDrag(event) behavior, it should return 'false' from this callback.
17026     *
17027     * <div class="special reference">
17028     * <h3>Developer Guides</h3>
17029     * <p>For a guide to implementing drag and drop features, read the
17030     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17031     * </div>
17032     */
17033    public interface OnDragListener {
17034        /**
17035         * Called when a drag event is dispatched to a view. This allows listeners
17036         * to get a chance to override base View behavior.
17037         *
17038         * @param v The View that received the drag event.
17039         * @param event The {@link android.view.DragEvent} object for the drag event.
17040         * @return {@code true} if the drag event was handled successfully, or {@code false}
17041         * if the drag event was not handled. Note that {@code false} will trigger the View
17042         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17043         */
17044        boolean onDrag(View v, DragEvent event);
17045    }
17046
17047    /**
17048     * Interface definition for a callback to be invoked when the focus state of
17049     * a view changed.
17050     */
17051    public interface OnFocusChangeListener {
17052        /**
17053         * Called when the focus state of a view has changed.
17054         *
17055         * @param v The view whose state has changed.
17056         * @param hasFocus The new focus state of v.
17057         */
17058        void onFocusChange(View v, boolean hasFocus);
17059    }
17060
17061    /**
17062     * Interface definition for a callback to be invoked when a view is clicked.
17063     */
17064    public interface OnClickListener {
17065        /**
17066         * Called when a view has been clicked.
17067         *
17068         * @param v The view that was clicked.
17069         */
17070        void onClick(View v);
17071    }
17072
17073    /**
17074     * Interface definition for a callback to be invoked when the context menu
17075     * for this view is being built.
17076     */
17077    public interface OnCreateContextMenuListener {
17078        /**
17079         * Called when the context menu for this view is being built. It is not
17080         * safe to hold onto the menu after this method returns.
17081         *
17082         * @param menu The context menu that is being built
17083         * @param v The view for which the context menu is being built
17084         * @param menuInfo Extra information about the item for which the
17085         *            context menu should be shown. This information will vary
17086         *            depending on the class of v.
17087         */
17088        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17089    }
17090
17091    /**
17092     * Interface definition for a callback to be invoked when the status bar changes
17093     * visibility.  This reports <strong>global</strong> changes to the system UI
17094     * state, not what the application is requesting.
17095     *
17096     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17097     */
17098    public interface OnSystemUiVisibilityChangeListener {
17099        /**
17100         * Called when the status bar changes visibility because of a call to
17101         * {@link View#setSystemUiVisibility(int)}.
17102         *
17103         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17104         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17105         * This tells you the <strong>global</strong> state of these UI visibility
17106         * flags, not what your app is currently applying.
17107         */
17108        public void onSystemUiVisibilityChange(int visibility);
17109    }
17110
17111    /**
17112     * Interface definition for a callback to be invoked when this view is attached
17113     * or detached from its window.
17114     */
17115    public interface OnAttachStateChangeListener {
17116        /**
17117         * Called when the view is attached to a window.
17118         * @param v The view that was attached
17119         */
17120        public void onViewAttachedToWindow(View v);
17121        /**
17122         * Called when the view is detached from a window.
17123         * @param v The view that was detached
17124         */
17125        public void onViewDetachedFromWindow(View v);
17126    }
17127
17128    private final class UnsetPressedState implements Runnable {
17129        public void run() {
17130            setPressed(false);
17131        }
17132    }
17133
17134    /**
17135     * Base class for derived classes that want to save and restore their own
17136     * state in {@link android.view.View#onSaveInstanceState()}.
17137     */
17138    public static class BaseSavedState extends AbsSavedState {
17139        /**
17140         * Constructor used when reading from a parcel. Reads the state of the superclass.
17141         *
17142         * @param source
17143         */
17144        public BaseSavedState(Parcel source) {
17145            super(source);
17146        }
17147
17148        /**
17149         * Constructor called by derived classes when creating their SavedState objects
17150         *
17151         * @param superState The state of the superclass of this view
17152         */
17153        public BaseSavedState(Parcelable superState) {
17154            super(superState);
17155        }
17156
17157        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17158                new Parcelable.Creator<BaseSavedState>() {
17159            public BaseSavedState createFromParcel(Parcel in) {
17160                return new BaseSavedState(in);
17161            }
17162
17163            public BaseSavedState[] newArray(int size) {
17164                return new BaseSavedState[size];
17165            }
17166        };
17167    }
17168
17169    /**
17170     * A set of information given to a view when it is attached to its parent
17171     * window.
17172     */
17173    static class AttachInfo {
17174        interface Callbacks {
17175            void playSoundEffect(int effectId);
17176            boolean performHapticFeedback(int effectId, boolean always);
17177        }
17178
17179        /**
17180         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17181         * to a Handler. This class contains the target (View) to invalidate and
17182         * the coordinates of the dirty rectangle.
17183         *
17184         * For performance purposes, this class also implements a pool of up to
17185         * POOL_LIMIT objects that get reused. This reduces memory allocations
17186         * whenever possible.
17187         */
17188        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17189            private static final int POOL_LIMIT = 10;
17190            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17191                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17192                        public InvalidateInfo newInstance() {
17193                            return new InvalidateInfo();
17194                        }
17195
17196                        public void onAcquired(InvalidateInfo element) {
17197                        }
17198
17199                        public void onReleased(InvalidateInfo element) {
17200                            element.target = null;
17201                        }
17202                    }, POOL_LIMIT)
17203            );
17204
17205            private InvalidateInfo mNext;
17206            private boolean mIsPooled;
17207
17208            View target;
17209
17210            int left;
17211            int top;
17212            int right;
17213            int bottom;
17214
17215            public void setNextPoolable(InvalidateInfo element) {
17216                mNext = element;
17217            }
17218
17219            public InvalidateInfo getNextPoolable() {
17220                return mNext;
17221            }
17222
17223            static InvalidateInfo acquire() {
17224                return sPool.acquire();
17225            }
17226
17227            void release() {
17228                sPool.release(this);
17229            }
17230
17231            public boolean isPooled() {
17232                return mIsPooled;
17233            }
17234
17235            public void setPooled(boolean isPooled) {
17236                mIsPooled = isPooled;
17237            }
17238        }
17239
17240        final IWindowSession mSession;
17241
17242        final IWindow mWindow;
17243
17244        final IBinder mWindowToken;
17245
17246        final Callbacks mRootCallbacks;
17247
17248        HardwareCanvas mHardwareCanvas;
17249
17250        /**
17251         * The top view of the hierarchy.
17252         */
17253        View mRootView;
17254
17255        IBinder mPanelParentWindowToken;
17256        Surface mSurface;
17257
17258        boolean mHardwareAccelerated;
17259        boolean mHardwareAccelerationRequested;
17260        HardwareRenderer mHardwareRenderer;
17261
17262        boolean mScreenOn;
17263
17264        /**
17265         * Scale factor used by the compatibility mode
17266         */
17267        float mApplicationScale;
17268
17269        /**
17270         * Indicates whether the application is in compatibility mode
17271         */
17272        boolean mScalingRequired;
17273
17274        /**
17275         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17276         */
17277        boolean mTurnOffWindowResizeAnim;
17278
17279        /**
17280         * Left position of this view's window
17281         */
17282        int mWindowLeft;
17283
17284        /**
17285         * Top position of this view's window
17286         */
17287        int mWindowTop;
17288
17289        /**
17290         * Indicates whether views need to use 32-bit drawing caches
17291         */
17292        boolean mUse32BitDrawingCache;
17293
17294        /**
17295         * For windows that are full-screen but using insets to layout inside
17296         * of the screen decorations, these are the current insets for the
17297         * content of the window.
17298         */
17299        final Rect mContentInsets = new Rect();
17300
17301        /**
17302         * For windows that are full-screen but using insets to layout inside
17303         * of the screen decorations, these are the current insets for the
17304         * actual visible parts of the window.
17305         */
17306        final Rect mVisibleInsets = new Rect();
17307
17308        /**
17309         * The internal insets given by this window.  This value is
17310         * supplied by the client (through
17311         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17312         * be given to the window manager when changed to be used in laying
17313         * out windows behind it.
17314         */
17315        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17316                = new ViewTreeObserver.InternalInsetsInfo();
17317
17318        /**
17319         * All views in the window's hierarchy that serve as scroll containers,
17320         * used to determine if the window can be resized or must be panned
17321         * to adjust for a soft input area.
17322         */
17323        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17324
17325        final KeyEvent.DispatcherState mKeyDispatchState
17326                = new KeyEvent.DispatcherState();
17327
17328        /**
17329         * Indicates whether the view's window currently has the focus.
17330         */
17331        boolean mHasWindowFocus;
17332
17333        /**
17334         * The current visibility of the window.
17335         */
17336        int mWindowVisibility;
17337
17338        /**
17339         * Indicates the time at which drawing started to occur.
17340         */
17341        long mDrawingTime;
17342
17343        /**
17344         * Indicates whether or not ignoring the DIRTY_MASK flags.
17345         */
17346        boolean mIgnoreDirtyState;
17347
17348        /**
17349         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17350         * to avoid clearing that flag prematurely.
17351         */
17352        boolean mSetIgnoreDirtyState = false;
17353
17354        /**
17355         * Indicates whether the view's window is currently in touch mode.
17356         */
17357        boolean mInTouchMode;
17358
17359        /**
17360         * Indicates that ViewAncestor should trigger a global layout change
17361         * the next time it performs a traversal
17362         */
17363        boolean mRecomputeGlobalAttributes;
17364
17365        /**
17366         * Always report new attributes at next traversal.
17367         */
17368        boolean mForceReportNewAttributes;
17369
17370        /**
17371         * Set during a traveral if any views want to keep the screen on.
17372         */
17373        boolean mKeepScreenOn;
17374
17375        /**
17376         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17377         */
17378        int mSystemUiVisibility;
17379
17380        /**
17381         * Hack to force certain system UI visibility flags to be cleared.
17382         */
17383        int mDisabledSystemUiVisibility;
17384
17385        /**
17386         * Last global system UI visibility reported by the window manager.
17387         */
17388        int mGlobalSystemUiVisibility;
17389
17390        /**
17391         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17392         * attached.
17393         */
17394        boolean mHasSystemUiListeners;
17395
17396        /**
17397         * Set if the visibility of any views has changed.
17398         */
17399        boolean mViewVisibilityChanged;
17400
17401        /**
17402         * Set to true if a view has been scrolled.
17403         */
17404        boolean mViewScrollChanged;
17405
17406        /**
17407         * Global to the view hierarchy used as a temporary for dealing with
17408         * x/y points in the transparent region computations.
17409         */
17410        final int[] mTransparentLocation = new int[2];
17411
17412        /**
17413         * Global to the view hierarchy used as a temporary for dealing with
17414         * x/y points in the ViewGroup.invalidateChild implementation.
17415         */
17416        final int[] mInvalidateChildLocation = new int[2];
17417
17418
17419        /**
17420         * Global to the view hierarchy used as a temporary for dealing with
17421         * x/y location when view is transformed.
17422         */
17423        final float[] mTmpTransformLocation = new float[2];
17424
17425        /**
17426         * The view tree observer used to dispatch global events like
17427         * layout, pre-draw, touch mode change, etc.
17428         */
17429        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17430
17431        /**
17432         * A Canvas used by the view hierarchy to perform bitmap caching.
17433         */
17434        Canvas mCanvas;
17435
17436        /**
17437         * The view root impl.
17438         */
17439        final ViewRootImpl mViewRootImpl;
17440
17441        /**
17442         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17443         * handler can be used to pump events in the UI events queue.
17444         */
17445        final Handler mHandler;
17446
17447        /**
17448         * Temporary for use in computing invalidate rectangles while
17449         * calling up the hierarchy.
17450         */
17451        final Rect mTmpInvalRect = new Rect();
17452
17453        /**
17454         * Temporary for use in computing hit areas with transformed views
17455         */
17456        final RectF mTmpTransformRect = new RectF();
17457
17458        /**
17459         * Temporary list for use in collecting focusable descendents of a view.
17460         */
17461        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17462
17463        /**
17464         * The id of the window for accessibility purposes.
17465         */
17466        int mAccessibilityWindowId = View.NO_ID;
17467
17468        /**
17469         * Whether to ingore not exposed for accessibility Views when
17470         * reporting the view tree to accessibility services.
17471         */
17472        boolean mIncludeNotImportantViews;
17473
17474        /**
17475         * The drawable for highlighting accessibility focus.
17476         */
17477        Drawable mAccessibilityFocusDrawable;
17478
17479        /**
17480         * Show where the margins, bounds and layout bounds are for each view.
17481         */
17482        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17483
17484        /**
17485         * Point used to compute visible regions.
17486         */
17487        final Point mPoint = new Point();
17488
17489        /**
17490         * Creates a new set of attachment information with the specified
17491         * events handler and thread.
17492         *
17493         * @param handler the events handler the view must use
17494         */
17495        AttachInfo(IWindowSession session, IWindow window,
17496                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17497            mSession = session;
17498            mWindow = window;
17499            mWindowToken = window.asBinder();
17500            mViewRootImpl = viewRootImpl;
17501            mHandler = handler;
17502            mRootCallbacks = effectPlayer;
17503        }
17504    }
17505
17506    /**
17507     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17508     * is supported. This avoids keeping too many unused fields in most
17509     * instances of View.</p>
17510     */
17511    private static class ScrollabilityCache implements Runnable {
17512
17513        /**
17514         * Scrollbars are not visible
17515         */
17516        public static final int OFF = 0;
17517
17518        /**
17519         * Scrollbars are visible
17520         */
17521        public static final int ON = 1;
17522
17523        /**
17524         * Scrollbars are fading away
17525         */
17526        public static final int FADING = 2;
17527
17528        public boolean fadeScrollBars;
17529
17530        public int fadingEdgeLength;
17531        public int scrollBarDefaultDelayBeforeFade;
17532        public int scrollBarFadeDuration;
17533
17534        public int scrollBarSize;
17535        public ScrollBarDrawable scrollBar;
17536        public float[] interpolatorValues;
17537        public View host;
17538
17539        public final Paint paint;
17540        public final Matrix matrix;
17541        public Shader shader;
17542
17543        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17544
17545        private static final float[] OPAQUE = { 255 };
17546        private static final float[] TRANSPARENT = { 0.0f };
17547
17548        /**
17549         * When fading should start. This time moves into the future every time
17550         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17551         */
17552        public long fadeStartTime;
17553
17554
17555        /**
17556         * The current state of the scrollbars: ON, OFF, or FADING
17557         */
17558        public int state = OFF;
17559
17560        private int mLastColor;
17561
17562        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17563            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17564            scrollBarSize = configuration.getScaledScrollBarSize();
17565            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17566            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17567
17568            paint = new Paint();
17569            matrix = new Matrix();
17570            // use use a height of 1, and then wack the matrix each time we
17571            // actually use it.
17572            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17573
17574            paint.setShader(shader);
17575            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17576            this.host = host;
17577        }
17578
17579        public void setFadeColor(int color) {
17580            if (color != 0 && color != mLastColor) {
17581                mLastColor = color;
17582                color |= 0xFF000000;
17583
17584                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17585                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17586
17587                paint.setShader(shader);
17588                // Restore the default transfer mode (src_over)
17589                paint.setXfermode(null);
17590            }
17591        }
17592
17593        public void run() {
17594            long now = AnimationUtils.currentAnimationTimeMillis();
17595            if (now >= fadeStartTime) {
17596
17597                // the animation fades the scrollbars out by changing
17598                // the opacity (alpha) from fully opaque to fully
17599                // transparent
17600                int nextFrame = (int) now;
17601                int framesCount = 0;
17602
17603                Interpolator interpolator = scrollBarInterpolator;
17604
17605                // Start opaque
17606                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17607
17608                // End transparent
17609                nextFrame += scrollBarFadeDuration;
17610                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17611
17612                state = FADING;
17613
17614                // Kick off the fade animation
17615                host.invalidate(true);
17616            }
17617        }
17618    }
17619
17620    /**
17621     * Resuable callback for sending
17622     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17623     */
17624    private class SendViewScrolledAccessibilityEvent implements Runnable {
17625        public volatile boolean mIsPending;
17626
17627        public void run() {
17628            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17629            mIsPending = false;
17630        }
17631    }
17632
17633    /**
17634     * <p>
17635     * This class represents a delegate that can be registered in a {@link View}
17636     * to enhance accessibility support via composition rather via inheritance.
17637     * It is specifically targeted to widget developers that extend basic View
17638     * classes i.e. classes in package android.view, that would like their
17639     * applications to be backwards compatible.
17640     * </p>
17641     * <div class="special reference">
17642     * <h3>Developer Guides</h3>
17643     * <p>For more information about making applications accessible, read the
17644     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17645     * developer guide.</p>
17646     * </div>
17647     * <p>
17648     * A scenario in which a developer would like to use an accessibility delegate
17649     * is overriding a method introduced in a later API version then the minimal API
17650     * version supported by the application. For example, the method
17651     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17652     * in API version 4 when the accessibility APIs were first introduced. If a
17653     * developer would like his application to run on API version 4 devices (assuming
17654     * all other APIs used by the application are version 4 or lower) and take advantage
17655     * of this method, instead of overriding the method which would break the application's
17656     * backwards compatibility, he can override the corresponding method in this
17657     * delegate and register the delegate in the target View if the API version of
17658     * the system is high enough i.e. the API version is same or higher to the API
17659     * version that introduced
17660     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17661     * </p>
17662     * <p>
17663     * Here is an example implementation:
17664     * </p>
17665     * <code><pre><p>
17666     * if (Build.VERSION.SDK_INT >= 14) {
17667     *     // If the API version is equal of higher than the version in
17668     *     // which onInitializeAccessibilityNodeInfo was introduced we
17669     *     // register a delegate with a customized implementation.
17670     *     View view = findViewById(R.id.view_id);
17671     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17672     *         public void onInitializeAccessibilityNodeInfo(View host,
17673     *                 AccessibilityNodeInfo info) {
17674     *             // Let the default implementation populate the info.
17675     *             super.onInitializeAccessibilityNodeInfo(host, info);
17676     *             // Set some other information.
17677     *             info.setEnabled(host.isEnabled());
17678     *         }
17679     *     });
17680     * }
17681     * </code></pre></p>
17682     * <p>
17683     * This delegate contains methods that correspond to the accessibility methods
17684     * in View. If a delegate has been specified the implementation in View hands
17685     * off handling to the corresponding method in this delegate. The default
17686     * implementation the delegate methods behaves exactly as the corresponding
17687     * method in View for the case of no accessibility delegate been set. Hence,
17688     * to customize the behavior of a View method, clients can override only the
17689     * corresponding delegate method without altering the behavior of the rest
17690     * accessibility related methods of the host view.
17691     * </p>
17692     */
17693    public static class AccessibilityDelegate {
17694
17695        /**
17696         * Sends an accessibility event of the given type. If accessibility is not
17697         * enabled this method has no effect.
17698         * <p>
17699         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17700         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17701         * been set.
17702         * </p>
17703         *
17704         * @param host The View hosting the delegate.
17705         * @param eventType The type of the event to send.
17706         *
17707         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17708         */
17709        public void sendAccessibilityEvent(View host, int eventType) {
17710            host.sendAccessibilityEventInternal(eventType);
17711        }
17712
17713        /**
17714         * Performs the specified accessibility action on the view. For
17715         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17716         * <p>
17717         * The default implementation behaves as
17718         * {@link View#performAccessibilityAction(int, Bundle)
17719         *  View#performAccessibilityAction(int, Bundle)} for the case of
17720         *  no accessibility delegate been set.
17721         * </p>
17722         *
17723         * @param action The action to perform.
17724         * @return Whether the action was performed.
17725         *
17726         * @see View#performAccessibilityAction(int, Bundle)
17727         *      View#performAccessibilityAction(int, Bundle)
17728         */
17729        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17730            return host.performAccessibilityActionInternal(action, args);
17731        }
17732
17733        /**
17734         * Sends an accessibility event. This method behaves exactly as
17735         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17736         * empty {@link AccessibilityEvent} and does not perform a check whether
17737         * accessibility is enabled.
17738         * <p>
17739         * The default implementation behaves as
17740         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17741         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17742         * the case of no accessibility delegate been set.
17743         * </p>
17744         *
17745         * @param host The View hosting the delegate.
17746         * @param event The event to send.
17747         *
17748         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17749         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17750         */
17751        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17752            host.sendAccessibilityEventUncheckedInternal(event);
17753        }
17754
17755        /**
17756         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17757         * to its children for adding their text content to the event.
17758         * <p>
17759         * The default implementation behaves as
17760         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17761         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17762         * the case of no accessibility delegate been set.
17763         * </p>
17764         *
17765         * @param host The View hosting the delegate.
17766         * @param event The event.
17767         * @return True if the event population was completed.
17768         *
17769         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17770         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17771         */
17772        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17773            return host.dispatchPopulateAccessibilityEventInternal(event);
17774        }
17775
17776        /**
17777         * Gives a chance to the host View to populate the accessibility event with its
17778         * text content.
17779         * <p>
17780         * The default implementation behaves as
17781         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17782         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17783         * the case of no accessibility delegate been set.
17784         * </p>
17785         *
17786         * @param host The View hosting the delegate.
17787         * @param event The accessibility event which to populate.
17788         *
17789         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17790         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17791         */
17792        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17793            host.onPopulateAccessibilityEventInternal(event);
17794        }
17795
17796        /**
17797         * Initializes an {@link AccessibilityEvent} with information about the
17798         * the host View which is the event source.
17799         * <p>
17800         * The default implementation behaves as
17801         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17802         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17803         * the case of no accessibility delegate been set.
17804         * </p>
17805         *
17806         * @param host The View hosting the delegate.
17807         * @param event The event to initialize.
17808         *
17809         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17810         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17811         */
17812        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17813            host.onInitializeAccessibilityEventInternal(event);
17814        }
17815
17816        /**
17817         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17818         * <p>
17819         * The default implementation behaves as
17820         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17821         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17822         * the case of no accessibility delegate been set.
17823         * </p>
17824         *
17825         * @param host The View hosting the delegate.
17826         * @param info The instance to initialize.
17827         *
17828         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17829         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17830         */
17831        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17832            host.onInitializeAccessibilityNodeInfoInternal(info);
17833        }
17834
17835        /**
17836         * Called when a child of the host View has requested sending an
17837         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17838         * to augment the event.
17839         * <p>
17840         * The default implementation behaves as
17841         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17842         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17843         * the case of no accessibility delegate been set.
17844         * </p>
17845         *
17846         * @param host The View hosting the delegate.
17847         * @param child The child which requests sending the event.
17848         * @param event The event to be sent.
17849         * @return True if the event should be sent
17850         *
17851         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17852         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17853         */
17854        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17855                AccessibilityEvent event) {
17856            return host.onRequestSendAccessibilityEventInternal(child, event);
17857        }
17858
17859        /**
17860         * Gets the provider for managing a virtual view hierarchy rooted at this View
17861         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17862         * that explore the window content.
17863         * <p>
17864         * The default implementation behaves as
17865         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17866         * the case of no accessibility delegate been set.
17867         * </p>
17868         *
17869         * @return The provider.
17870         *
17871         * @see AccessibilityNodeProvider
17872         */
17873        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17874            return null;
17875        }
17876    }
17877}
17878