View.java revision 8ffe8b304e4778b3c95e57ad5a77cd41c9cf9f7b
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     * @hide
1052     */
1053    public static final int FOCUS_ACCESSIBILITY =  0x00001000;
1054
1055    /**
1056     * Use with {@link #focusSearch(int)}. Move acessibility focus left.
1057     *
1058     * @hide
1059     */
1060    public static final int ACCESSIBILITY_FOCUS_LEFT = FOCUS_LEFT | FOCUS_ACCESSIBILITY;
1061
1062    /**
1063     * Use with {@link #focusSearch(int)}. Move acessibility focus up.
1064     *
1065     * @hide
1066     */
1067    public static final int ACCESSIBILITY_FOCUS_UP = FOCUS_UP | FOCUS_ACCESSIBILITY;
1068
1069    /**
1070     * Use with {@link #focusSearch(int)}. Move acessibility focus right.
1071     *
1072     * @hide
1073     */
1074    public static final int ACCESSIBILITY_FOCUS_RIGHT = FOCUS_RIGHT | FOCUS_ACCESSIBILITY;
1075
1076    /**
1077     * Use with {@link #focusSearch(int)}. Move acessibility focus down.
1078     *
1079     * @hide
1080     */
1081    public static final int ACCESSIBILITY_FOCUS_DOWN = FOCUS_DOWN | FOCUS_ACCESSIBILITY;
1082
1083    /**
1084     * Use with {@link #focusSearch(int)}. Move acessibility focus forward.
1085     *
1086     * @hide
1087     */
1088    public static final int ACCESSIBILITY_FOCUS_FORWARD = FOCUS_FORWARD | FOCUS_ACCESSIBILITY;
1089
1090    /**
1091     * Use with {@link #focusSearch(int)}. Move acessibility focus backward.
1092     *
1093     * @hide
1094     */
1095    public static final int ACCESSIBILITY_FOCUS_BACKWARD = FOCUS_BACKWARD | FOCUS_ACCESSIBILITY;
1096
1097    /**
1098     * Bits of {@link #getMeasuredWidthAndState()} and
1099     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1100     */
1101    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1102
1103    /**
1104     * Bits of {@link #getMeasuredWidthAndState()} and
1105     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1106     */
1107    public static final int MEASURED_STATE_MASK = 0xff000000;
1108
1109    /**
1110     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1111     * for functions that combine both width and height into a single int,
1112     * such as {@link #getMeasuredState()} and the childState argument of
1113     * {@link #resolveSizeAndState(int, int, int)}.
1114     */
1115    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1116
1117    /**
1118     * Bit of {@link #getMeasuredWidthAndState()} and
1119     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1120     * is smaller that the space the view would like to have.
1121     */
1122    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1123
1124    /**
1125     * Base View state sets
1126     */
1127    // Singles
1128    /**
1129     * Indicates the view has no states set. States are used with
1130     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1131     * view depending on its state.
1132     *
1133     * @see android.graphics.drawable.Drawable
1134     * @see #getDrawableState()
1135     */
1136    protected static final int[] EMPTY_STATE_SET;
1137    /**
1138     * Indicates the view is enabled. States are used with
1139     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1140     * view depending on its state.
1141     *
1142     * @see android.graphics.drawable.Drawable
1143     * @see #getDrawableState()
1144     */
1145    protected static final int[] ENABLED_STATE_SET;
1146    /**
1147     * Indicates the view is focused. States are used with
1148     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1149     * view depending on its state.
1150     *
1151     * @see android.graphics.drawable.Drawable
1152     * @see #getDrawableState()
1153     */
1154    protected static final int[] FOCUSED_STATE_SET;
1155    /**
1156     * Indicates the view is selected. States are used with
1157     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1158     * view depending on its state.
1159     *
1160     * @see android.graphics.drawable.Drawable
1161     * @see #getDrawableState()
1162     */
1163    protected static final int[] SELECTED_STATE_SET;
1164    /**
1165     * Indicates the view is pressed. States are used with
1166     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1167     * view depending on its state.
1168     *
1169     * @see android.graphics.drawable.Drawable
1170     * @see #getDrawableState()
1171     * @hide
1172     */
1173    protected static final int[] PRESSED_STATE_SET;
1174    /**
1175     * Indicates the view's window has focus. States are used with
1176     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1177     * view depending on its state.
1178     *
1179     * @see android.graphics.drawable.Drawable
1180     * @see #getDrawableState()
1181     */
1182    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1183    // Doubles
1184    /**
1185     * Indicates the view is enabled and has the focus.
1186     *
1187     * @see #ENABLED_STATE_SET
1188     * @see #FOCUSED_STATE_SET
1189     */
1190    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1191    /**
1192     * Indicates the view is enabled and selected.
1193     *
1194     * @see #ENABLED_STATE_SET
1195     * @see #SELECTED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_SELECTED_STATE_SET;
1198    /**
1199     * Indicates the view is enabled and that its window has focus.
1200     *
1201     * @see #ENABLED_STATE_SET
1202     * @see #WINDOW_FOCUSED_STATE_SET
1203     */
1204    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1205    /**
1206     * Indicates the view is focused and selected.
1207     *
1208     * @see #FOCUSED_STATE_SET
1209     * @see #SELECTED_STATE_SET
1210     */
1211    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1212    /**
1213     * Indicates the view has the focus and that its window has the focus.
1214     *
1215     * @see #FOCUSED_STATE_SET
1216     * @see #WINDOW_FOCUSED_STATE_SET
1217     */
1218    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1219    /**
1220     * Indicates the view is selected and that its window has the focus.
1221     *
1222     * @see #SELECTED_STATE_SET
1223     * @see #WINDOW_FOCUSED_STATE_SET
1224     */
1225    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1226    // Triples
1227    /**
1228     * Indicates the view is enabled, focused and selected.
1229     *
1230     * @see #ENABLED_STATE_SET
1231     * @see #FOCUSED_STATE_SET
1232     * @see #SELECTED_STATE_SET
1233     */
1234    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1235    /**
1236     * Indicates the view is enabled, focused and its window has the focus.
1237     *
1238     * @see #ENABLED_STATE_SET
1239     * @see #FOCUSED_STATE_SET
1240     * @see #WINDOW_FOCUSED_STATE_SET
1241     */
1242    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1243    /**
1244     * Indicates the view is enabled, selected and its window has the focus.
1245     *
1246     * @see #ENABLED_STATE_SET
1247     * @see #SELECTED_STATE_SET
1248     * @see #WINDOW_FOCUSED_STATE_SET
1249     */
1250    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1251    /**
1252     * Indicates the view is focused, selected and its window has the focus.
1253     *
1254     * @see #FOCUSED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     * @see #WINDOW_FOCUSED_STATE_SET
1257     */
1258    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1259    /**
1260     * Indicates the view is enabled, focused, selected and its window
1261     * has the focus.
1262     *
1263     * @see #ENABLED_STATE_SET
1264     * @see #FOCUSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     * @see #WINDOW_FOCUSED_STATE_SET
1267     */
1268    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #WINDOW_FOCUSED_STATE_SET
1274     */
1275    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1276    /**
1277     * Indicates the view is pressed and selected.
1278     *
1279     * @see #PRESSED_STATE_SET
1280     * @see #SELECTED_STATE_SET
1281     */
1282    protected static final int[] PRESSED_SELECTED_STATE_SET;
1283    /**
1284     * Indicates the view is pressed, selected and its window has the focus.
1285     *
1286     * @see #PRESSED_STATE_SET
1287     * @see #SELECTED_STATE_SET
1288     * @see #WINDOW_FOCUSED_STATE_SET
1289     */
1290    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1291    /**
1292     * Indicates the view is pressed and focused.
1293     *
1294     * @see #PRESSED_STATE_SET
1295     * @see #FOCUSED_STATE_SET
1296     */
1297    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1298    /**
1299     * Indicates the view is pressed, focused and its window has the focus.
1300     *
1301     * @see #PRESSED_STATE_SET
1302     * @see #FOCUSED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is pressed, focused and selected.
1308     *
1309     * @see #PRESSED_STATE_SET
1310     * @see #SELECTED_STATE_SET
1311     * @see #FOCUSED_STATE_SET
1312     */
1313    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed, focused, selected and its window has the focus.
1316     *
1317     * @see #PRESSED_STATE_SET
1318     * @see #FOCUSED_STATE_SET
1319     * @see #SELECTED_STATE_SET
1320     * @see #WINDOW_FOCUSED_STATE_SET
1321     */
1322    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1323    /**
1324     * Indicates the view is pressed and enabled.
1325     *
1326     * @see #PRESSED_STATE_SET
1327     * @see #ENABLED_STATE_SET
1328     */
1329    protected static final int[] PRESSED_ENABLED_STATE_SET;
1330    /**
1331     * Indicates the view is pressed, enabled and its window has the focus.
1332     *
1333     * @see #PRESSED_STATE_SET
1334     * @see #ENABLED_STATE_SET
1335     * @see #WINDOW_FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, enabled and selected.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #ENABLED_STATE_SET
1343     * @see #SELECTED_STATE_SET
1344     */
1345    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1346    /**
1347     * Indicates the view is pressed, enabled, selected and its window has the
1348     * focus.
1349     *
1350     * @see #PRESSED_STATE_SET
1351     * @see #ENABLED_STATE_SET
1352     * @see #SELECTED_STATE_SET
1353     * @see #WINDOW_FOCUSED_STATE_SET
1354     */
1355    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1356    /**
1357     * Indicates the view is pressed, enabled and focused.
1358     *
1359     * @see #PRESSED_STATE_SET
1360     * @see #ENABLED_STATE_SET
1361     * @see #FOCUSED_STATE_SET
1362     */
1363    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1364    /**
1365     * Indicates the view is pressed, enabled, focused and its window has the
1366     * focus.
1367     *
1368     * @see #PRESSED_STATE_SET
1369     * @see #ENABLED_STATE_SET
1370     * @see #FOCUSED_STATE_SET
1371     * @see #WINDOW_FOCUSED_STATE_SET
1372     */
1373    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1374    /**
1375     * Indicates the view is pressed, enabled, focused and selected.
1376     *
1377     * @see #PRESSED_STATE_SET
1378     * @see #ENABLED_STATE_SET
1379     * @see #SELECTED_STATE_SET
1380     * @see #FOCUSED_STATE_SET
1381     */
1382    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1383    /**
1384     * Indicates the view is pressed, enabled, focused, selected and its window
1385     * has the focus.
1386     *
1387     * @see #PRESSED_STATE_SET
1388     * @see #ENABLED_STATE_SET
1389     * @see #SELECTED_STATE_SET
1390     * @see #FOCUSED_STATE_SET
1391     * @see #WINDOW_FOCUSED_STATE_SET
1392     */
1393    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1394
1395    /**
1396     * The order here is very important to {@link #getDrawableState()}
1397     */
1398    private static final int[][] VIEW_STATE_SETS;
1399
1400    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1401    static final int VIEW_STATE_SELECTED = 1 << 1;
1402    static final int VIEW_STATE_FOCUSED = 1 << 2;
1403    static final int VIEW_STATE_ENABLED = 1 << 3;
1404    static final int VIEW_STATE_PRESSED = 1 << 4;
1405    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1406    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1407    static final int VIEW_STATE_HOVERED = 1 << 7;
1408    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1409    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1410
1411    static final int[] VIEW_STATE_IDS = new int[] {
1412        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1413        R.attr.state_selected,          VIEW_STATE_SELECTED,
1414        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1415        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1416        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1417        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1418        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1419        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1420        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1421        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1422    };
1423
1424    static {
1425        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1426            throw new IllegalStateException(
1427                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1428        }
1429        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1430        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1431            int viewState = R.styleable.ViewDrawableStates[i];
1432            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1433                if (VIEW_STATE_IDS[j] == viewState) {
1434                    orderedIds[i * 2] = viewState;
1435                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1436                }
1437            }
1438        }
1439        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1440        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1441        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1442            int numBits = Integer.bitCount(i);
1443            int[] set = new int[numBits];
1444            int pos = 0;
1445            for (int j = 0; j < orderedIds.length; j += 2) {
1446                if ((i & orderedIds[j+1]) != 0) {
1447                    set[pos++] = orderedIds[j];
1448                }
1449            }
1450            VIEW_STATE_SETS[i] = set;
1451        }
1452
1453        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1454        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1455        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1456        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1457                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1458        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1459        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1461        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1463        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1465                | VIEW_STATE_FOCUSED];
1466        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1467        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1469        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1471        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1473                | VIEW_STATE_ENABLED];
1474        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1476        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1477                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1478                | VIEW_STATE_ENABLED];
1479        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1481                | VIEW_STATE_ENABLED];
1482        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1483                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1484                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1485
1486        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1487        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1488                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1489        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1490                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1491        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1492                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1493                | VIEW_STATE_PRESSED];
1494        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1495                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1496        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1497                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1498                | VIEW_STATE_PRESSED];
1499        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1500                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1501                | VIEW_STATE_PRESSED];
1502        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1503                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1504                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1505        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1506                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1507        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1508                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1509                | VIEW_STATE_PRESSED];
1510        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1511                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1512                | VIEW_STATE_PRESSED];
1513        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1514                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1515                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1516        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1517                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1518                | VIEW_STATE_PRESSED];
1519        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1520                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1521                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1522        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1523                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1524                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1525        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1526                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1527                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1528                | VIEW_STATE_PRESSED];
1529    }
1530
1531    /**
1532     * Accessibility event types that are dispatched for text population.
1533     */
1534    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1535            AccessibilityEvent.TYPE_VIEW_CLICKED
1536            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1537            | AccessibilityEvent.TYPE_VIEW_SELECTED
1538            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1539            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1540            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1541            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1542            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1543            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1544            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1545            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1546
1547    /**
1548     * Temporary Rect currently for use in setBackground().  This will probably
1549     * be extended in the future to hold our own class with more than just
1550     * a Rect. :)
1551     */
1552    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1553
1554    /**
1555     * Map used to store views' tags.
1556     */
1557    private SparseArray<Object> mKeyedTags;
1558
1559    /**
1560     * The next available accessiiblity id.
1561     */
1562    private static int sNextAccessibilityViewId;
1563
1564    /**
1565     * The animation currently associated with this view.
1566     * @hide
1567     */
1568    protected Animation mCurrentAnimation = null;
1569
1570    /**
1571     * Width as measured during measure pass.
1572     * {@hide}
1573     */
1574    @ViewDebug.ExportedProperty(category = "measurement")
1575    int mMeasuredWidth;
1576
1577    /**
1578     * Height as measured during measure pass.
1579     * {@hide}
1580     */
1581    @ViewDebug.ExportedProperty(category = "measurement")
1582    int mMeasuredHeight;
1583
1584    /**
1585     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1586     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1587     * its display list. This flag, used only when hw accelerated, allows us to clear the
1588     * flag while retaining this information until it's needed (at getDisplayList() time and
1589     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1590     *
1591     * {@hide}
1592     */
1593    boolean mRecreateDisplayList = false;
1594
1595    /**
1596     * The view's identifier.
1597     * {@hide}
1598     *
1599     * @see #setId(int)
1600     * @see #getId()
1601     */
1602    @ViewDebug.ExportedProperty(resolveId = true)
1603    int mID = NO_ID;
1604
1605    /**
1606     * The stable ID of this view for accessibility purposes.
1607     */
1608    int mAccessibilityViewId = NO_ID;
1609
1610    /**
1611     * @hide
1612     */
1613    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1614
1615    /**
1616     * The view's tag.
1617     * {@hide}
1618     *
1619     * @see #setTag(Object)
1620     * @see #getTag()
1621     */
1622    protected Object mTag;
1623
1624    // for mPrivateFlags:
1625    /** {@hide} */
1626    static final int WANTS_FOCUS                    = 0x00000001;
1627    /** {@hide} */
1628    static final int FOCUSED                        = 0x00000002;
1629    /** {@hide} */
1630    static final int SELECTED                       = 0x00000004;
1631    /** {@hide} */
1632    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1633    /** {@hide} */
1634    static final int HAS_BOUNDS                     = 0x00000010;
1635    /** {@hide} */
1636    static final int DRAWN                          = 0x00000020;
1637    /**
1638     * When this flag is set, this view is running an animation on behalf of its
1639     * children and should therefore not cancel invalidate requests, even if they
1640     * lie outside of this view's bounds.
1641     *
1642     * {@hide}
1643     */
1644    static final int DRAW_ANIMATION                 = 0x00000040;
1645    /** {@hide} */
1646    static final int SKIP_DRAW                      = 0x00000080;
1647    /** {@hide} */
1648    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1649    /** {@hide} */
1650    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1651    /** {@hide} */
1652    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1653    /** {@hide} */
1654    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1655    /** {@hide} */
1656    static final int FORCE_LAYOUT                   = 0x00001000;
1657    /** {@hide} */
1658    static final int LAYOUT_REQUIRED                = 0x00002000;
1659
1660    private static final int PRESSED                = 0x00004000;
1661
1662    /** {@hide} */
1663    static final int DRAWING_CACHE_VALID            = 0x00008000;
1664    /**
1665     * Flag used to indicate that this view should be drawn once more (and only once
1666     * more) after its animation has completed.
1667     * {@hide}
1668     */
1669    static final int ANIMATION_STARTED              = 0x00010000;
1670
1671    private static final int SAVE_STATE_CALLED      = 0x00020000;
1672
1673    /**
1674     * Indicates that the View returned true when onSetAlpha() was called and that
1675     * the alpha must be restored.
1676     * {@hide}
1677     */
1678    static final int ALPHA_SET                      = 0x00040000;
1679
1680    /**
1681     * Set by {@link #setScrollContainer(boolean)}.
1682     */
1683    static final int SCROLL_CONTAINER               = 0x00080000;
1684
1685    /**
1686     * Set by {@link #setScrollContainer(boolean)}.
1687     */
1688    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1689
1690    /**
1691     * View flag indicating whether this view was invalidated (fully or partially.)
1692     *
1693     * @hide
1694     */
1695    static final int DIRTY                          = 0x00200000;
1696
1697    /**
1698     * View flag indicating whether this view was invalidated by an opaque
1699     * invalidate request.
1700     *
1701     * @hide
1702     */
1703    static final int DIRTY_OPAQUE                   = 0x00400000;
1704
1705    /**
1706     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1707     *
1708     * @hide
1709     */
1710    static final int DIRTY_MASK                     = 0x00600000;
1711
1712    /**
1713     * Indicates whether the background is opaque.
1714     *
1715     * @hide
1716     */
1717    static final int OPAQUE_BACKGROUND              = 0x00800000;
1718
1719    /**
1720     * Indicates whether the scrollbars are opaque.
1721     *
1722     * @hide
1723     */
1724    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1725
1726    /**
1727     * Indicates whether the view is opaque.
1728     *
1729     * @hide
1730     */
1731    static final int OPAQUE_MASK                    = 0x01800000;
1732
1733    /**
1734     * Indicates a prepressed state;
1735     * the short time between ACTION_DOWN and recognizing
1736     * a 'real' press. Prepressed is used to recognize quick taps
1737     * even when they are shorter than ViewConfiguration.getTapTimeout().
1738     *
1739     * @hide
1740     */
1741    private static final int PREPRESSED             = 0x02000000;
1742
1743    /**
1744     * Indicates whether the view is temporarily detached.
1745     *
1746     * @hide
1747     */
1748    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1749
1750    /**
1751     * Indicates that we should awaken scroll bars once attached
1752     *
1753     * @hide
1754     */
1755    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1756
1757    /**
1758     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1759     * @hide
1760     */
1761    private static final int HOVERED              = 0x10000000;
1762
1763    /**
1764     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1765     * for transform operations
1766     *
1767     * @hide
1768     */
1769    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1770
1771    /** {@hide} */
1772    static final int ACTIVATED                    = 0x40000000;
1773
1774    /**
1775     * Indicates that this view was specifically invalidated, not just dirtied because some
1776     * child view was invalidated. The flag is used to determine when we need to recreate
1777     * a view's display list (as opposed to just returning a reference to its existing
1778     * display list).
1779     *
1780     * @hide
1781     */
1782    static final int INVALIDATED                  = 0x80000000;
1783
1784    /* Masks for mPrivateFlags2 */
1785
1786    /**
1787     * Indicates that this view has reported that it can accept the current drag's content.
1788     * Cleared when the drag operation concludes.
1789     * @hide
1790     */
1791    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1792
1793    /**
1794     * Indicates that this view is currently directly under the drag location in a
1795     * drag-and-drop operation involving content that it can accept.  Cleared when
1796     * the drag exits the view, or when the drag operation concludes.
1797     * @hide
1798     */
1799    static final int DRAG_HOVERED                 = 0x00000002;
1800
1801    /**
1802     * Horizontal layout direction of this view is from Left to Right.
1803     * Use with {@link #setLayoutDirection}.
1804     * @hide
1805     */
1806    public static final int LAYOUT_DIRECTION_LTR = 0;
1807
1808    /**
1809     * Horizontal layout direction of this view is from Right to Left.
1810     * Use with {@link #setLayoutDirection}.
1811     * @hide
1812     */
1813    public static final int LAYOUT_DIRECTION_RTL = 1;
1814
1815    /**
1816     * Horizontal layout direction of this view is inherited from its parent.
1817     * Use with {@link #setLayoutDirection}.
1818     * @hide
1819     */
1820    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1821
1822    /**
1823     * Horizontal layout direction of this view is from deduced from the default language
1824     * script for the locale. Use with {@link #setLayoutDirection}.
1825     * @hide
1826     */
1827    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1828
1829    /**
1830     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1831     * @hide
1832     */
1833    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1834
1835    /**
1836     * Mask for use with private flags indicating bits used for horizontal layout direction.
1837     * @hide
1838     */
1839    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1840
1841    /**
1842     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1843     * right-to-left direction.
1844     * @hide
1845     */
1846    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1847
1848    /**
1849     * Indicates whether the view horizontal layout direction has been resolved.
1850     * @hide
1851     */
1852    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1853
1854    /**
1855     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1856     * @hide
1857     */
1858    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1859
1860    /*
1861     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1862     * flag value.
1863     * @hide
1864     */
1865    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1866            LAYOUT_DIRECTION_LTR,
1867            LAYOUT_DIRECTION_RTL,
1868            LAYOUT_DIRECTION_INHERIT,
1869            LAYOUT_DIRECTION_LOCALE
1870    };
1871
1872    /**
1873     * Default horizontal layout direction.
1874     * @hide
1875     */
1876    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1877
1878    /**
1879     * Indicates that the view is tracking some sort of transient state
1880     * that the app should not need to be aware of, but that the framework
1881     * should take special care to preserve.
1882     *
1883     * @hide
1884     */
1885    static final int HAS_TRANSIENT_STATE = 0x00000100;
1886
1887
1888    /**
1889     * Text direction is inherited thru {@link ViewGroup}
1890     * @hide
1891     */
1892    public static final int TEXT_DIRECTION_INHERIT = 0;
1893
1894    /**
1895     * Text direction is using "first strong algorithm". The first strong directional character
1896     * determines the paragraph direction. If there is no strong directional character, the
1897     * paragraph direction is the view's resolved layout direction.
1898     * @hide
1899     */
1900    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1901
1902    /**
1903     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1904     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1905     * If there are neither, the paragraph direction is the view's resolved layout direction.
1906     * @hide
1907     */
1908    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1909
1910    /**
1911     * Text direction is forced to LTR.
1912     * @hide
1913     */
1914    public static final int TEXT_DIRECTION_LTR = 3;
1915
1916    /**
1917     * Text direction is forced to RTL.
1918     * @hide
1919     */
1920    public static final int TEXT_DIRECTION_RTL = 4;
1921
1922    /**
1923     * Text direction is coming from the system Locale.
1924     * @hide
1925     */
1926    public static final int TEXT_DIRECTION_LOCALE = 5;
1927
1928    /**
1929     * Default text direction is inherited
1930     * @hide
1931     */
1932    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1933
1934    /**
1935     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1936     * @hide
1937     */
1938    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1939
1940    /**
1941     * Mask for use with private flags indicating bits used for text direction.
1942     * @hide
1943     */
1944    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1945
1946    /**
1947     * Array of text direction flags for mapping attribute "textDirection" to correct
1948     * flag value.
1949     * @hide
1950     */
1951    private static final int[] TEXT_DIRECTION_FLAGS = {
1952            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1954            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1955            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1956            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1957            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1958    };
1959
1960    /**
1961     * Indicates whether the view text direction has been resolved.
1962     * @hide
1963     */
1964    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1965
1966    /**
1967     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1968     * @hide
1969     */
1970    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1971
1972    /**
1973     * Mask for use with private flags indicating bits used for resolved text direction.
1974     * @hide
1975     */
1976    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1977
1978    /**
1979     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1980     * @hide
1981     */
1982    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1983            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1984
1985    /*
1986     * Default text alignment. The text alignment of this View is inherited from its parent.
1987     * Use with {@link #setTextAlignment(int)}
1988     * @hide
1989     */
1990    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1991
1992    /**
1993     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1994     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1995     *
1996     * Use with {@link #setTextAlignment(int)}
1997     * @hide
1998     */
1999    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
2000
2001    /**
2002     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
2003     *
2004     * Use with {@link #setTextAlignment(int)}
2005     * @hide
2006     */
2007    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2008
2009    /**
2010     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2011     *
2012     * Use with {@link #setTextAlignment(int)}
2013     * @hide
2014     */
2015    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2016
2017    /**
2018     * Center the paragraph, e.g. ALIGN_CENTER.
2019     *
2020     * Use with {@link #setTextAlignment(int)}
2021     * @hide
2022     */
2023    public static final int TEXT_ALIGNMENT_CENTER = 4;
2024
2025    /**
2026     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2027     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2028     *
2029     * Use with {@link #setTextAlignment(int)}
2030     * @hide
2031     */
2032    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2033
2034    /**
2035     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2036     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2037     *
2038     * Use with {@link #setTextAlignment(int)}
2039     * @hide
2040     */
2041    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2042
2043    /**
2044     * Default text alignment is inherited
2045     * @hide
2046     */
2047    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2048
2049    /**
2050      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2051      * @hide
2052      */
2053    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
2054
2055    /**
2056      * Mask for use with private flags indicating bits used for text alignment.
2057      * @hide
2058      */
2059    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
2060
2061    /**
2062     * Array of text direction flags for mapping attribute "textAlignment" to correct
2063     * flag value.
2064     * @hide
2065     */
2066    private static final int[] TEXT_ALIGNMENT_FLAGS = {
2067            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
2070            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
2071            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
2072            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
2073            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2074    };
2075
2076    /**
2077     * Indicates whether the view text alignment has been resolved.
2078     * @hide
2079     */
2080    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2081
2082    /**
2083     * Bit shift to get the resolved text alignment.
2084     * @hide
2085     */
2086    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2087
2088    /**
2089     * Mask for use with private flags indicating bits used for text alignment.
2090     * @hide
2091     */
2092    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2093
2094    /**
2095     * Indicates whether if the view text alignment has been resolved to gravity
2096     */
2097    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2098            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2099
2100    // Accessiblity constants for mPrivateFlags2
2101
2102    /**
2103     * Shift for the bits in {@link #mPrivateFlags2} related to the
2104     * "importantForAccessibility" attribute.
2105     */
2106    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2107
2108    /**
2109     * Automatically determine whether a view is important for accessibility.
2110     */
2111    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2112
2113    /**
2114     * The view is important for accessibility.
2115     */
2116    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2117
2118    /**
2119     * The view is not important for accessibility.
2120     */
2121    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2122
2123    /**
2124     * The default whether the view is important for accessiblity.
2125     */
2126    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2127
2128    /**
2129     * Mask for obtainig the bits which specify how to determine
2130     * whether a view is important for accessibility.
2131     */
2132    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2133        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2134        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2135
2136    /**
2137     * Flag indicating whether a view has accessibility focus.
2138     */
2139    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2140
2141    /**
2142     * Flag indicating whether a view state for accessibility has changed.
2143     */
2144    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2145
2146    /**
2147     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2148     * is used to check whether later changes to the view's transform should invalidate the
2149     * view to force the quickReject test to run again.
2150     */
2151    static final int VIEW_QUICK_REJECTED = 0x10000000;
2152
2153    // Accessiblity constants for mPrivateFlags2
2154
2155    /**
2156     * Shift for the bits in {@link #mPrivateFlags2} related to the
2157     * "accessibilityFocusable" attribute.
2158     */
2159    static final int ACCESSIBILITY_FOCUSABLE_SHIFT = 29;
2160
2161    /**
2162     * The system determines whether the view can take accessibility focus - default (recommended).
2163     * <p>
2164     * Such a view is consideted by the focus search if it is:
2165     * <ul>
2166     * <li>
2167     * Important for accessibility and actionable (clickable, long clickable, focusable)
2168     * </li>
2169     * <li>
2170     * Important for accessibility, not actionable (clickable, long clickable, focusable),
2171     * and does not have an actionable predecessor.
2172     * </li>
2173     * </ul>
2174     * An accessibility srvice can request putting accessibility focus on such a view.
2175     * </p>
2176     *
2177     * @hide
2178     */
2179    public static final int ACCESSIBILITY_FOCUSABLE_AUTO = 0x00000000;
2180
2181    /**
2182     * The view can take accessibility focus.
2183     * <p>
2184     * A view that can take accessibility focus is always considered during focus
2185     * search and an accessibility service can request putting accessibility focus
2186     * on it.
2187     * </p>
2188     *
2189     * @hide
2190     */
2191    public static final int ACCESSIBILITY_FOCUSABLE_YES = 0x00000001;
2192
2193    /**
2194     * The view can not take accessibility focus.
2195     * <p>
2196     * A view that can not take accessibility focus is never considered during focus
2197     * search and an accessibility service can not request putting accessibility focus
2198     * on it.
2199     * </p>
2200     *
2201     * @hide
2202     */
2203    public static final int ACCESSIBILITY_FOCUSABLE_NO = 0x00000002;
2204
2205    /**
2206     * The default whether the view is accessiblity focusable.
2207     */
2208    static final int ACCESSIBILITY_FOCUSABLE_DEFAULT = ACCESSIBILITY_FOCUSABLE_AUTO;
2209
2210    /**
2211     * Mask for obtainig the bits which specifies how to determine
2212     * whether a view is accessibility focusable.
2213     */
2214    static final int ACCESSIBILITY_FOCUSABLE_MASK = (ACCESSIBILITY_FOCUSABLE_AUTO
2215        | ACCESSIBILITY_FOCUSABLE_YES | ACCESSIBILITY_FOCUSABLE_NO)
2216        << ACCESSIBILITY_FOCUSABLE_SHIFT;
2217
2218
2219    /* End of masks for mPrivateFlags2 */
2220
2221    /* Masks for mPrivateFlags3 */
2222
2223    /**
2224     * Flag indicating that view has a transform animation set on it. This is used to track whether
2225     * an animation is cleared between successive frames, in order to tell the associated
2226     * DisplayList to clear its animation matrix.
2227     */
2228    static final int VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2229
2230    /**
2231     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2232     * animation is cleared between successive frames, in order to tell the associated
2233     * DisplayList to restore its alpha value.
2234     */
2235    static final int VIEW_IS_ANIMATING_ALPHA = 0x2;
2236
2237
2238    /* End of masks for mPrivateFlags3 */
2239
2240    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2241
2242    /**
2243     * Always allow a user to over-scroll this view, provided it is a
2244     * view that can scroll.
2245     *
2246     * @see #getOverScrollMode()
2247     * @see #setOverScrollMode(int)
2248     */
2249    public static final int OVER_SCROLL_ALWAYS = 0;
2250
2251    /**
2252     * Allow a user to over-scroll this view only if the content is large
2253     * enough to meaningfully scroll, provided it is a view that can scroll.
2254     *
2255     * @see #getOverScrollMode()
2256     * @see #setOverScrollMode(int)
2257     */
2258    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2259
2260    /**
2261     * Never allow a user to over-scroll this view.
2262     *
2263     * @see #getOverScrollMode()
2264     * @see #setOverScrollMode(int)
2265     */
2266    public static final int OVER_SCROLL_NEVER = 2;
2267
2268    /**
2269     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2270     * requested the system UI (status bar) to be visible (the default).
2271     *
2272     * @see #setSystemUiVisibility(int)
2273     */
2274    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2275
2276    /**
2277     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2278     * system UI to enter an unobtrusive "low profile" mode.
2279     *
2280     * <p>This is for use in games, book readers, video players, or any other
2281     * "immersive" application where the usual system chrome is deemed too distracting.
2282     *
2283     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2284     *
2285     * @see #setSystemUiVisibility(int)
2286     */
2287    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2288
2289    /**
2290     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2291     * system navigation be temporarily hidden.
2292     *
2293     * <p>This is an even less obtrusive state than that called for by
2294     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2295     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2296     * those to disappear. This is useful (in conjunction with the
2297     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2298     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2299     * window flags) for displaying content using every last pixel on the display.
2300     *
2301     * <p>There is a limitation: because navigation controls are so important, the least user
2302     * interaction will cause them to reappear immediately.  When this happens, both
2303     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2304     * so that both elements reappear at the same time.
2305     *
2306     * @see #setSystemUiVisibility(int)
2307     */
2308    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2309
2310    /**
2311     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2312     * into the normal fullscreen mode so that its content can take over the screen
2313     * while still allowing the user to interact with the application.
2314     *
2315     * <p>This has the same visual effect as
2316     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2317     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2318     * meaning that non-critical screen decorations (such as the status bar) will be
2319     * hidden while the user is in the View's window, focusing the experience on
2320     * that content.  Unlike the window flag, if you are using ActionBar in
2321     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2322     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2323     * hide the action bar.
2324     *
2325     * <p>This approach to going fullscreen is best used over the window flag when
2326     * it is a transient state -- that is, the application does this at certain
2327     * points in its user interaction where it wants to allow the user to focus
2328     * on content, but not as a continuous state.  For situations where the application
2329     * would like to simply stay full screen the entire time (such as a game that
2330     * wants to take over the screen), the
2331     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2332     * is usually a better approach.  The state set here will be removed by the system
2333     * in various situations (such as the user moving to another application) like
2334     * the other system UI states.
2335     *
2336     * <p>When using this flag, the application should provide some easy facility
2337     * for the user to go out of it.  A common example would be in an e-book
2338     * reader, where tapping on the screen brings back whatever screen and UI
2339     * decorations that had been hidden while the user was immersed in reading
2340     * the book.
2341     *
2342     * @see #setSystemUiVisibility(int)
2343     */
2344    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2345
2346    /**
2347     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2348     * flags, we would like a stable view of the content insets given to
2349     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2350     * will always represent the worst case that the application can expect
2351     * as a continuous state.  In the stock Android UI this is the space for
2352     * the system bar, nav bar, and status bar, but not more transient elements
2353     * such as an input method.
2354     *
2355     * The stable layout your UI sees is based on the system UI modes you can
2356     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2357     * then you will get a stable layout for changes of the
2358     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2359     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2360     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2361     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2362     * with a stable layout.  (Note that you should avoid using
2363     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2364     *
2365     * If you have set the window flag {@ WindowManager.LayoutParams#FLAG_FULLSCREEN}
2366     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2367     * then a hidden status bar will be considered a "stable" state for purposes
2368     * here.  This allows your UI to continually hide the status bar, while still
2369     * using the system UI flags to hide the action bar while still retaining
2370     * a stable layout.  Note that changing the window fullscreen flag will never
2371     * provide a stable layout for a clean transition.
2372     *
2373     * <p>If you are using ActionBar in
2374     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2375     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2376     * insets it adds to those given to the application.
2377     */
2378    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2379
2380    /**
2381     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2382     * to be layed out as if it has requested
2383     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2384     * allows it to avoid artifacts when switching in and out of that mode, at
2385     * the expense that some of its user interface may be covered by screen
2386     * decorations when they are shown.  You can perform layout of your inner
2387     * UI elements to account for the navagation system UI through the
2388     * {@link #fitSystemWindows(Rect)} method.
2389     */
2390    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2391
2392    /**
2393     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2394     * to be layed out as if it has requested
2395     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2396     * allows it to avoid artifacts when switching in and out of that mode, at
2397     * the expense that some of its user interface may be covered by screen
2398     * decorations when they are shown.  You can perform layout of your inner
2399     * UI elements to account for non-fullscreen system UI through the
2400     * {@link #fitSystemWindows(Rect)} method.
2401     */
2402    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2403
2404    /**
2405     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2406     */
2407    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2408
2409    /**
2410     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2411     */
2412    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2413
2414    /**
2415     * @hide
2416     *
2417     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2418     * out of the public fields to keep the undefined bits out of the developer's way.
2419     *
2420     * Flag to make the status bar not expandable.  Unless you also
2421     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2422     */
2423    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2424
2425    /**
2426     * @hide
2427     *
2428     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2429     * out of the public fields to keep the undefined bits out of the developer's way.
2430     *
2431     * Flag to hide notification icons and scrolling ticker text.
2432     */
2433    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2434
2435    /**
2436     * @hide
2437     *
2438     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2439     * out of the public fields to keep the undefined bits out of the developer's way.
2440     *
2441     * Flag to disable incoming notification alerts.  This will not block
2442     * icons, but it will block sound, vibrating and other visual or aural notifications.
2443     */
2444    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2445
2446    /**
2447     * @hide
2448     *
2449     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2450     * out of the public fields to keep the undefined bits out of the developer's way.
2451     *
2452     * Flag to hide only the scrolling ticker.  Note that
2453     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2454     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2455     */
2456    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2457
2458    /**
2459     * @hide
2460     *
2461     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2462     * out of the public fields to keep the undefined bits out of the developer's way.
2463     *
2464     * Flag to hide the center system info area.
2465     */
2466    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2467
2468    /**
2469     * @hide
2470     *
2471     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2472     * out of the public fields to keep the undefined bits out of the developer's way.
2473     *
2474     * Flag to hide only the home button.  Don't use this
2475     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2476     */
2477    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2478
2479    /**
2480     * @hide
2481     *
2482     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2483     * out of the public fields to keep the undefined bits out of the developer's way.
2484     *
2485     * Flag to hide only the back button. Don't use this
2486     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2487     */
2488    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2489
2490    /**
2491     * @hide
2492     *
2493     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2494     * out of the public fields to keep the undefined bits out of the developer's way.
2495     *
2496     * Flag to hide only the clock.  You might use this if your activity has
2497     * its own clock making the status bar's clock redundant.
2498     */
2499    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2500
2501    /**
2502     * @hide
2503     *
2504     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2505     * out of the public fields to keep the undefined bits out of the developer's way.
2506     *
2507     * Flag to hide only the recent apps button. Don't use this
2508     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2509     */
2510    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2511
2512    /**
2513     * @hide
2514     */
2515    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2516
2517    /**
2518     * These are the system UI flags that can be cleared by events outside
2519     * of an application.  Currently this is just the ability to tap on the
2520     * screen while hiding the navigation bar to have it return.
2521     * @hide
2522     */
2523    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2524            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2525            | SYSTEM_UI_FLAG_FULLSCREEN;
2526
2527    /**
2528     * Flags that can impact the layout in relation to system UI.
2529     */
2530    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2531            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2532            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2533
2534    /**
2535     * Find views that render the specified text.
2536     *
2537     * @see #findViewsWithText(ArrayList, CharSequence, int)
2538     */
2539    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2540
2541    /**
2542     * Find find views that contain the specified content description.
2543     *
2544     * @see #findViewsWithText(ArrayList, CharSequence, int)
2545     */
2546    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2547
2548    /**
2549     * Find views that contain {@link AccessibilityNodeProvider}. Such
2550     * a View is a root of virtual view hierarchy and may contain the searched
2551     * text. If this flag is set Views with providers are automatically
2552     * added and it is a responsibility of the client to call the APIs of
2553     * the provider to determine whether the virtual tree rooted at this View
2554     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2555     * represeting the virtual views with this text.
2556     *
2557     * @see #findViewsWithText(ArrayList, CharSequence, int)
2558     *
2559     * @hide
2560     */
2561    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2562
2563    /**
2564     * The undefined cursor position.
2565     */
2566    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2567
2568    /**
2569     * Indicates that the screen has changed state and is now off.
2570     *
2571     * @see #onScreenStateChanged(int)
2572     */
2573    public static final int SCREEN_STATE_OFF = 0x0;
2574
2575    /**
2576     * Indicates that the screen has changed state and is now on.
2577     *
2578     * @see #onScreenStateChanged(int)
2579     */
2580    public static final int SCREEN_STATE_ON = 0x1;
2581
2582    /**
2583     * Controls the over-scroll mode for this view.
2584     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2585     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2586     * and {@link #OVER_SCROLL_NEVER}.
2587     */
2588    private int mOverScrollMode;
2589
2590    /**
2591     * The parent this view is attached to.
2592     * {@hide}
2593     *
2594     * @see #getParent()
2595     */
2596    protected ViewParent mParent;
2597
2598    /**
2599     * {@hide}
2600     */
2601    AttachInfo mAttachInfo;
2602
2603    /**
2604     * {@hide}
2605     */
2606    @ViewDebug.ExportedProperty(flagMapping = {
2607        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2608                name = "FORCE_LAYOUT"),
2609        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2610                name = "LAYOUT_REQUIRED"),
2611        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2612            name = "DRAWING_CACHE_INVALID", outputIf = false),
2613        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2614        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2615        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2616        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2617    })
2618    int mPrivateFlags;
2619    int mPrivateFlags2;
2620    int mPrivateFlags3;
2621
2622    /**
2623     * This view's request for the visibility of the status bar.
2624     * @hide
2625     */
2626    @ViewDebug.ExportedProperty(flagMapping = {
2627        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2628                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2629                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2630        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2631                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2632                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2633        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2634                                equals = SYSTEM_UI_FLAG_VISIBLE,
2635                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2636    })
2637    int mSystemUiVisibility;
2638
2639    /**
2640     * Reference count for transient state.
2641     * @see #setHasTransientState(boolean)
2642     */
2643    int mTransientStateCount = 0;
2644
2645    /**
2646     * Count of how many windows this view has been attached to.
2647     */
2648    int mWindowAttachCount;
2649
2650    /**
2651     * The layout parameters associated with this view and used by the parent
2652     * {@link android.view.ViewGroup} to determine how this view should be
2653     * laid out.
2654     * {@hide}
2655     */
2656    protected ViewGroup.LayoutParams mLayoutParams;
2657
2658    /**
2659     * The view flags hold various views states.
2660     * {@hide}
2661     */
2662    @ViewDebug.ExportedProperty
2663    int mViewFlags;
2664
2665    static class TransformationInfo {
2666        /**
2667         * The transform matrix for the View. This transform is calculated internally
2668         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2669         * is used by default. Do *not* use this variable directly; instead call
2670         * getMatrix(), which will automatically recalculate the matrix if necessary
2671         * to get the correct matrix based on the latest rotation and scale properties.
2672         */
2673        private final Matrix mMatrix = new Matrix();
2674
2675        /**
2676         * The transform matrix for the View. This transform is calculated internally
2677         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2678         * is used by default. Do *not* use this variable directly; instead call
2679         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2680         * to get the correct matrix based on the latest rotation and scale properties.
2681         */
2682        private Matrix mInverseMatrix;
2683
2684        /**
2685         * An internal variable that tracks whether we need to recalculate the
2686         * transform matrix, based on whether the rotation or scaleX/Y properties
2687         * have changed since the matrix was last calculated.
2688         */
2689        boolean mMatrixDirty = false;
2690
2691        /**
2692         * An internal variable that tracks whether we need to recalculate the
2693         * transform matrix, based on whether the rotation or scaleX/Y properties
2694         * have changed since the matrix was last calculated.
2695         */
2696        private boolean mInverseMatrixDirty = true;
2697
2698        /**
2699         * A variable that tracks whether we need to recalculate the
2700         * transform matrix, based on whether the rotation or scaleX/Y properties
2701         * have changed since the matrix was last calculated. This variable
2702         * is only valid after a call to updateMatrix() or to a function that
2703         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2704         */
2705        private boolean mMatrixIsIdentity = true;
2706
2707        /**
2708         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2709         */
2710        private Camera mCamera = null;
2711
2712        /**
2713         * This matrix is used when computing the matrix for 3D rotations.
2714         */
2715        private Matrix matrix3D = null;
2716
2717        /**
2718         * These prev values are used to recalculate a centered pivot point when necessary. The
2719         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2720         * set), so thes values are only used then as well.
2721         */
2722        private int mPrevWidth = -1;
2723        private int mPrevHeight = -1;
2724
2725        /**
2726         * The degrees rotation around the vertical axis through the pivot point.
2727         */
2728        @ViewDebug.ExportedProperty
2729        float mRotationY = 0f;
2730
2731        /**
2732         * The degrees rotation around the horizontal axis through the pivot point.
2733         */
2734        @ViewDebug.ExportedProperty
2735        float mRotationX = 0f;
2736
2737        /**
2738         * The degrees rotation around the pivot point.
2739         */
2740        @ViewDebug.ExportedProperty
2741        float mRotation = 0f;
2742
2743        /**
2744         * The amount of translation of the object away from its left property (post-layout).
2745         */
2746        @ViewDebug.ExportedProperty
2747        float mTranslationX = 0f;
2748
2749        /**
2750         * The amount of translation of the object away from its top property (post-layout).
2751         */
2752        @ViewDebug.ExportedProperty
2753        float mTranslationY = 0f;
2754
2755        /**
2756         * The amount of scale in the x direction around the pivot point. A
2757         * value of 1 means no scaling is applied.
2758         */
2759        @ViewDebug.ExportedProperty
2760        float mScaleX = 1f;
2761
2762        /**
2763         * The amount of scale in the y direction around the pivot point. A
2764         * value of 1 means no scaling is applied.
2765         */
2766        @ViewDebug.ExportedProperty
2767        float mScaleY = 1f;
2768
2769        /**
2770         * The x location of the point around which the view is rotated and scaled.
2771         */
2772        @ViewDebug.ExportedProperty
2773        float mPivotX = 0f;
2774
2775        /**
2776         * The y location of the point around which the view is rotated and scaled.
2777         */
2778        @ViewDebug.ExportedProperty
2779        float mPivotY = 0f;
2780
2781        /**
2782         * The opacity of the View. This is a value from 0 to 1, where 0 means
2783         * completely transparent and 1 means completely opaque.
2784         */
2785        @ViewDebug.ExportedProperty
2786        float mAlpha = 1f;
2787    }
2788
2789    TransformationInfo mTransformationInfo;
2790
2791    private boolean mLastIsOpaque;
2792
2793    /**
2794     * Convenience value to check for float values that are close enough to zero to be considered
2795     * zero.
2796     */
2797    private static final float NONZERO_EPSILON = .001f;
2798
2799    /**
2800     * The distance in pixels from the left edge of this view's parent
2801     * to the left edge of this view.
2802     * {@hide}
2803     */
2804    @ViewDebug.ExportedProperty(category = "layout")
2805    protected int mLeft;
2806    /**
2807     * The distance in pixels from the left edge of this view's parent
2808     * to the right edge of this view.
2809     * {@hide}
2810     */
2811    @ViewDebug.ExportedProperty(category = "layout")
2812    protected int mRight;
2813    /**
2814     * The distance in pixels from the top edge of this view's parent
2815     * to the top edge of this view.
2816     * {@hide}
2817     */
2818    @ViewDebug.ExportedProperty(category = "layout")
2819    protected int mTop;
2820    /**
2821     * The distance in pixels from the top edge of this view's parent
2822     * to the bottom edge of this view.
2823     * {@hide}
2824     */
2825    @ViewDebug.ExportedProperty(category = "layout")
2826    protected int mBottom;
2827
2828    /**
2829     * The offset, in pixels, by which the content of this view is scrolled
2830     * horizontally.
2831     * {@hide}
2832     */
2833    @ViewDebug.ExportedProperty(category = "scrolling")
2834    protected int mScrollX;
2835    /**
2836     * The offset, in pixels, by which the content of this view is scrolled
2837     * vertically.
2838     * {@hide}
2839     */
2840    @ViewDebug.ExportedProperty(category = "scrolling")
2841    protected int mScrollY;
2842
2843    /**
2844     * The left padding in pixels, that is the distance in pixels between the
2845     * left edge of this view and the left edge of its content.
2846     * {@hide}
2847     */
2848    @ViewDebug.ExportedProperty(category = "padding")
2849    protected int mPaddingLeft;
2850    /**
2851     * The right padding in pixels, that is the distance in pixels between the
2852     * right edge of this view and the right edge of its content.
2853     * {@hide}
2854     */
2855    @ViewDebug.ExportedProperty(category = "padding")
2856    protected int mPaddingRight;
2857    /**
2858     * The top padding in pixels, that is the distance in pixels between the
2859     * top edge of this view and the top edge of its content.
2860     * {@hide}
2861     */
2862    @ViewDebug.ExportedProperty(category = "padding")
2863    protected int mPaddingTop;
2864    /**
2865     * The bottom padding in pixels, that is the distance in pixels between the
2866     * bottom edge of this view and the bottom edge of its content.
2867     * {@hide}
2868     */
2869    @ViewDebug.ExportedProperty(category = "padding")
2870    protected int mPaddingBottom;
2871
2872    /**
2873     * The layout insets in pixels, that is the distance in pixels between the
2874     * visible edges of this view its bounds.
2875     */
2876    private Insets mLayoutInsets;
2877
2878    /**
2879     * Briefly describes the view and is primarily used for accessibility support.
2880     */
2881    private CharSequence mContentDescription;
2882
2883    /**
2884     * Cache the paddingRight set by the user to append to the scrollbar's size.
2885     *
2886     * @hide
2887     */
2888    @ViewDebug.ExportedProperty(category = "padding")
2889    protected int mUserPaddingRight;
2890
2891    /**
2892     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2893     *
2894     * @hide
2895     */
2896    @ViewDebug.ExportedProperty(category = "padding")
2897    protected int mUserPaddingBottom;
2898
2899    /**
2900     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2901     *
2902     * @hide
2903     */
2904    @ViewDebug.ExportedProperty(category = "padding")
2905    protected int mUserPaddingLeft;
2906
2907    /**
2908     * Cache if the user padding is relative.
2909     *
2910     */
2911    @ViewDebug.ExportedProperty(category = "padding")
2912    boolean mUserPaddingRelative;
2913
2914    /**
2915     * Cache the paddingStart set by the user to append to the scrollbar's size.
2916     *
2917     */
2918    @ViewDebug.ExportedProperty(category = "padding")
2919    int mUserPaddingStart;
2920
2921    /**
2922     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2923     *
2924     */
2925    @ViewDebug.ExportedProperty(category = "padding")
2926    int mUserPaddingEnd;
2927
2928    /**
2929     * @hide
2930     */
2931    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2932    /**
2933     * @hide
2934     */
2935    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2936
2937    private Drawable mBackground;
2938
2939    private int mBackgroundResource;
2940    private boolean mBackgroundSizeChanged;
2941
2942    static class ListenerInfo {
2943        /**
2944         * Listener used to dispatch focus change events.
2945         * This field should be made private, so it is hidden from the SDK.
2946         * {@hide}
2947         */
2948        protected OnFocusChangeListener mOnFocusChangeListener;
2949
2950        /**
2951         * Listeners for layout change events.
2952         */
2953        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2954
2955        /**
2956         * Listeners for attach events.
2957         */
2958        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2959
2960        /**
2961         * Listener used to dispatch click events.
2962         * This field should be made private, so it is hidden from the SDK.
2963         * {@hide}
2964         */
2965        public OnClickListener mOnClickListener;
2966
2967        /**
2968         * Listener used to dispatch long click events.
2969         * This field should be made private, so it is hidden from the SDK.
2970         * {@hide}
2971         */
2972        protected OnLongClickListener mOnLongClickListener;
2973
2974        /**
2975         * Listener used to build the context menu.
2976         * This field should be made private, so it is hidden from the SDK.
2977         * {@hide}
2978         */
2979        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2980
2981        private OnKeyListener mOnKeyListener;
2982
2983        private OnTouchListener mOnTouchListener;
2984
2985        private OnHoverListener mOnHoverListener;
2986
2987        private OnGenericMotionListener mOnGenericMotionListener;
2988
2989        private OnDragListener mOnDragListener;
2990
2991        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2992    }
2993
2994    ListenerInfo mListenerInfo;
2995
2996    /**
2997     * The application environment this view lives in.
2998     * This field should be made private, so it is hidden from the SDK.
2999     * {@hide}
3000     */
3001    protected Context mContext;
3002
3003    private final Resources mResources;
3004
3005    private ScrollabilityCache mScrollCache;
3006
3007    private int[] mDrawableState = null;
3008
3009    /**
3010     * Set to true when drawing cache is enabled and cannot be created.
3011     *
3012     * @hide
3013     */
3014    public boolean mCachingFailed;
3015
3016    private Bitmap mDrawingCache;
3017    private Bitmap mUnscaledDrawingCache;
3018    private HardwareLayer mHardwareLayer;
3019    DisplayList mDisplayList;
3020
3021    /**
3022     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3023     * the user may specify which view to go to next.
3024     */
3025    private int mNextFocusLeftId = View.NO_ID;
3026
3027    /**
3028     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3029     * the user may specify which view to go to next.
3030     */
3031    private int mNextFocusRightId = View.NO_ID;
3032
3033    /**
3034     * When this view has focus and the next focus is {@link #FOCUS_UP},
3035     * the user may specify which view to go to next.
3036     */
3037    private int mNextFocusUpId = View.NO_ID;
3038
3039    /**
3040     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3041     * the user may specify which view to go to next.
3042     */
3043    private int mNextFocusDownId = View.NO_ID;
3044
3045    /**
3046     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3047     * the user may specify which view to go to next.
3048     */
3049    int mNextFocusForwardId = View.NO_ID;
3050
3051    private CheckForLongPress mPendingCheckForLongPress;
3052    private CheckForTap mPendingCheckForTap = null;
3053    private PerformClick mPerformClick;
3054    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3055
3056    private UnsetPressedState mUnsetPressedState;
3057
3058    /**
3059     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3060     * up event while a long press is invoked as soon as the long press duration is reached, so
3061     * a long press could be performed before the tap is checked, in which case the tap's action
3062     * should not be invoked.
3063     */
3064    private boolean mHasPerformedLongPress;
3065
3066    /**
3067     * The minimum height of the view. We'll try our best to have the height
3068     * of this view to at least this amount.
3069     */
3070    @ViewDebug.ExportedProperty(category = "measurement")
3071    private int mMinHeight;
3072
3073    /**
3074     * The minimum width of the view. We'll try our best to have the width
3075     * of this view to at least this amount.
3076     */
3077    @ViewDebug.ExportedProperty(category = "measurement")
3078    private int mMinWidth;
3079
3080    /**
3081     * The delegate to handle touch events that are physically in this view
3082     * but should be handled by another view.
3083     */
3084    private TouchDelegate mTouchDelegate = null;
3085
3086    /**
3087     * Solid color to use as a background when creating the drawing cache. Enables
3088     * the cache to use 16 bit bitmaps instead of 32 bit.
3089     */
3090    private int mDrawingCacheBackgroundColor = 0;
3091
3092    /**
3093     * Special tree observer used when mAttachInfo is null.
3094     */
3095    private ViewTreeObserver mFloatingTreeObserver;
3096
3097    /**
3098     * Cache the touch slop from the context that created the view.
3099     */
3100    private int mTouchSlop;
3101
3102    /**
3103     * Object that handles automatic animation of view properties.
3104     */
3105    private ViewPropertyAnimator mAnimator = null;
3106
3107    /**
3108     * Flag indicating that a drag can cross window boundaries.  When
3109     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3110     * with this flag set, all visible applications will be able to participate
3111     * in the drag operation and receive the dragged content.
3112     *
3113     * @hide
3114     */
3115    public static final int DRAG_FLAG_GLOBAL = 1;
3116
3117    /**
3118     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3119     */
3120    private float mVerticalScrollFactor;
3121
3122    /**
3123     * Position of the vertical scroll bar.
3124     */
3125    private int mVerticalScrollbarPosition;
3126
3127    /**
3128     * Position the scroll bar at the default position as determined by the system.
3129     */
3130    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3131
3132    /**
3133     * Position the scroll bar along the left edge.
3134     */
3135    public static final int SCROLLBAR_POSITION_LEFT = 1;
3136
3137    /**
3138     * Position the scroll bar along the right edge.
3139     */
3140    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3141
3142    /**
3143     * Indicates that the view does not have a layer.
3144     *
3145     * @see #getLayerType()
3146     * @see #setLayerType(int, android.graphics.Paint)
3147     * @see #LAYER_TYPE_SOFTWARE
3148     * @see #LAYER_TYPE_HARDWARE
3149     */
3150    public static final int LAYER_TYPE_NONE = 0;
3151
3152    /**
3153     * <p>Indicates that the view has a software layer. A software layer is backed
3154     * by a bitmap and causes the view to be rendered using Android's software
3155     * rendering pipeline, even if hardware acceleration is enabled.</p>
3156     *
3157     * <p>Software layers have various usages:</p>
3158     * <p>When the application is not using hardware acceleration, a software layer
3159     * is useful to apply a specific color filter and/or blending mode and/or
3160     * translucency to a view and all its children.</p>
3161     * <p>When the application is using hardware acceleration, a software layer
3162     * is useful to render drawing primitives not supported by the hardware
3163     * accelerated pipeline. It can also be used to cache a complex view tree
3164     * into a texture and reduce the complexity of drawing operations. For instance,
3165     * when animating a complex view tree with a translation, a software layer can
3166     * be used to render the view tree only once.</p>
3167     * <p>Software layers should be avoided when the affected view tree updates
3168     * often. Every update will require to re-render the software layer, which can
3169     * potentially be slow (particularly when hardware acceleration is turned on
3170     * since the layer will have to be uploaded into a hardware texture after every
3171     * update.)</p>
3172     *
3173     * @see #getLayerType()
3174     * @see #setLayerType(int, android.graphics.Paint)
3175     * @see #LAYER_TYPE_NONE
3176     * @see #LAYER_TYPE_HARDWARE
3177     */
3178    public static final int LAYER_TYPE_SOFTWARE = 1;
3179
3180    /**
3181     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3182     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3183     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3184     * rendering pipeline, but only if hardware acceleration is turned on for the
3185     * view hierarchy. When hardware acceleration is turned off, hardware layers
3186     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3187     *
3188     * <p>A hardware layer is useful to apply a specific color filter and/or
3189     * blending mode and/or translucency to a view and all its children.</p>
3190     * <p>A hardware layer can be used to cache a complex view tree into a
3191     * texture and reduce the complexity of drawing operations. For instance,
3192     * when animating a complex view tree with a translation, a hardware layer can
3193     * be used to render the view tree only once.</p>
3194     * <p>A hardware layer can also be used to increase the rendering quality when
3195     * rotation transformations are applied on a view. It can also be used to
3196     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3197     *
3198     * @see #getLayerType()
3199     * @see #setLayerType(int, android.graphics.Paint)
3200     * @see #LAYER_TYPE_NONE
3201     * @see #LAYER_TYPE_SOFTWARE
3202     */
3203    public static final int LAYER_TYPE_HARDWARE = 2;
3204
3205    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3206            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3207            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3208            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3209    })
3210    int mLayerType = LAYER_TYPE_NONE;
3211    Paint mLayerPaint;
3212    Rect mLocalDirtyRect;
3213
3214    /**
3215     * Set to true when the view is sending hover accessibility events because it
3216     * is the innermost hovered view.
3217     */
3218    private boolean mSendingHoverAccessibilityEvents;
3219
3220    /**
3221     * Simple constructor to use when creating a view from code.
3222     *
3223     * @param context The Context the view is running in, through which it can
3224     *        access the current theme, resources, etc.
3225     */
3226    public View(Context context) {
3227        mContext = context;
3228        mResources = context != null ? context.getResources() : null;
3229        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3230        // Set layout and text direction defaults
3231        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3232                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3233                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3234                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT) |
3235                (ACCESSIBILITY_FOCUSABLE_DEFAULT << ACCESSIBILITY_FOCUSABLE_SHIFT);
3236        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3237        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3238        mUserPaddingStart = -1;
3239        mUserPaddingEnd = -1;
3240        mUserPaddingRelative = false;
3241    }
3242
3243    /**
3244     * Delegate for injecting accessiblity functionality.
3245     */
3246    AccessibilityDelegate mAccessibilityDelegate;
3247
3248    /**
3249     * Consistency verifier for debugging purposes.
3250     * @hide
3251     */
3252    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3253            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3254                    new InputEventConsistencyVerifier(this, 0) : null;
3255
3256    /**
3257     * Constructor that is called when inflating a view from XML. This is called
3258     * when a view is being constructed from an XML file, supplying attributes
3259     * that were specified in the XML file. This version uses a default style of
3260     * 0, so the only attribute values applied are those in the Context's Theme
3261     * and the given AttributeSet.
3262     *
3263     * <p>
3264     * The method onFinishInflate() will be called after all children have been
3265     * added.
3266     *
3267     * @param context The Context the view is running in, through which it can
3268     *        access the current theme, resources, etc.
3269     * @param attrs The attributes of the XML tag that is inflating the view.
3270     * @see #View(Context, AttributeSet, int)
3271     */
3272    public View(Context context, AttributeSet attrs) {
3273        this(context, attrs, 0);
3274    }
3275
3276    /**
3277     * Perform inflation from XML and apply a class-specific base style. This
3278     * constructor of View allows subclasses to use their own base style when
3279     * they are inflating. For example, a Button class's constructor would call
3280     * this version of the super class constructor and supply
3281     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3282     * the theme's button style to modify all of the base view attributes (in
3283     * particular its background) as well as the Button class's attributes.
3284     *
3285     * @param context The Context the view is running in, through which it can
3286     *        access the current theme, resources, etc.
3287     * @param attrs The attributes of the XML tag that is inflating the view.
3288     * @param defStyle The default style to apply to this view. If 0, no style
3289     *        will be applied (beyond what is included in the theme). This may
3290     *        either be an attribute resource, whose value will be retrieved
3291     *        from the current theme, or an explicit style resource.
3292     * @see #View(Context, AttributeSet)
3293     */
3294    public View(Context context, AttributeSet attrs, int defStyle) {
3295        this(context);
3296
3297        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3298                defStyle, 0);
3299
3300        Drawable background = null;
3301
3302        int leftPadding = -1;
3303        int topPadding = -1;
3304        int rightPadding = -1;
3305        int bottomPadding = -1;
3306        int startPadding = -1;
3307        int endPadding = -1;
3308
3309        int padding = -1;
3310
3311        int viewFlagValues = 0;
3312        int viewFlagMasks = 0;
3313
3314        boolean setScrollContainer = false;
3315
3316        int x = 0;
3317        int y = 0;
3318
3319        float tx = 0;
3320        float ty = 0;
3321        float rotation = 0;
3322        float rotationX = 0;
3323        float rotationY = 0;
3324        float sx = 1f;
3325        float sy = 1f;
3326        boolean transformSet = false;
3327
3328        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3329
3330        int overScrollMode = mOverScrollMode;
3331        final int N = a.getIndexCount();
3332        for (int i = 0; i < N; i++) {
3333            int attr = a.getIndex(i);
3334            switch (attr) {
3335                case com.android.internal.R.styleable.View_background:
3336                    background = a.getDrawable(attr);
3337                    break;
3338                case com.android.internal.R.styleable.View_padding:
3339                    padding = a.getDimensionPixelSize(attr, -1);
3340                    break;
3341                 case com.android.internal.R.styleable.View_paddingLeft:
3342                    leftPadding = a.getDimensionPixelSize(attr, -1);
3343                    break;
3344                case com.android.internal.R.styleable.View_paddingTop:
3345                    topPadding = a.getDimensionPixelSize(attr, -1);
3346                    break;
3347                case com.android.internal.R.styleable.View_paddingRight:
3348                    rightPadding = a.getDimensionPixelSize(attr, -1);
3349                    break;
3350                case com.android.internal.R.styleable.View_paddingBottom:
3351                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3352                    break;
3353                case com.android.internal.R.styleable.View_paddingStart:
3354                    startPadding = a.getDimensionPixelSize(attr, -1);
3355                    break;
3356                case com.android.internal.R.styleable.View_paddingEnd:
3357                    endPadding = a.getDimensionPixelSize(attr, -1);
3358                    break;
3359                case com.android.internal.R.styleable.View_scrollX:
3360                    x = a.getDimensionPixelOffset(attr, 0);
3361                    break;
3362                case com.android.internal.R.styleable.View_scrollY:
3363                    y = a.getDimensionPixelOffset(attr, 0);
3364                    break;
3365                case com.android.internal.R.styleable.View_alpha:
3366                    setAlpha(a.getFloat(attr, 1f));
3367                    break;
3368                case com.android.internal.R.styleable.View_transformPivotX:
3369                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3370                    break;
3371                case com.android.internal.R.styleable.View_transformPivotY:
3372                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3373                    break;
3374                case com.android.internal.R.styleable.View_translationX:
3375                    tx = a.getDimensionPixelOffset(attr, 0);
3376                    transformSet = true;
3377                    break;
3378                case com.android.internal.R.styleable.View_translationY:
3379                    ty = a.getDimensionPixelOffset(attr, 0);
3380                    transformSet = true;
3381                    break;
3382                case com.android.internal.R.styleable.View_rotation:
3383                    rotation = a.getFloat(attr, 0);
3384                    transformSet = true;
3385                    break;
3386                case com.android.internal.R.styleable.View_rotationX:
3387                    rotationX = a.getFloat(attr, 0);
3388                    transformSet = true;
3389                    break;
3390                case com.android.internal.R.styleable.View_rotationY:
3391                    rotationY = a.getFloat(attr, 0);
3392                    transformSet = true;
3393                    break;
3394                case com.android.internal.R.styleable.View_scaleX:
3395                    sx = a.getFloat(attr, 1f);
3396                    transformSet = true;
3397                    break;
3398                case com.android.internal.R.styleable.View_scaleY:
3399                    sy = a.getFloat(attr, 1f);
3400                    transformSet = true;
3401                    break;
3402                case com.android.internal.R.styleable.View_id:
3403                    mID = a.getResourceId(attr, NO_ID);
3404                    break;
3405                case com.android.internal.R.styleable.View_tag:
3406                    mTag = a.getText(attr);
3407                    break;
3408                case com.android.internal.R.styleable.View_fitsSystemWindows:
3409                    if (a.getBoolean(attr, false)) {
3410                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3411                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3412                    }
3413                    break;
3414                case com.android.internal.R.styleable.View_focusable:
3415                    if (a.getBoolean(attr, false)) {
3416                        viewFlagValues |= FOCUSABLE;
3417                        viewFlagMasks |= FOCUSABLE_MASK;
3418                    }
3419                    break;
3420                case com.android.internal.R.styleable.View_focusableInTouchMode:
3421                    if (a.getBoolean(attr, false)) {
3422                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3423                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3424                    }
3425                    break;
3426                case com.android.internal.R.styleable.View_clickable:
3427                    if (a.getBoolean(attr, false)) {
3428                        viewFlagValues |= CLICKABLE;
3429                        viewFlagMasks |= CLICKABLE;
3430                    }
3431                    break;
3432                case com.android.internal.R.styleable.View_longClickable:
3433                    if (a.getBoolean(attr, false)) {
3434                        viewFlagValues |= LONG_CLICKABLE;
3435                        viewFlagMasks |= LONG_CLICKABLE;
3436                    }
3437                    break;
3438                case com.android.internal.R.styleable.View_saveEnabled:
3439                    if (!a.getBoolean(attr, true)) {
3440                        viewFlagValues |= SAVE_DISABLED;
3441                        viewFlagMasks |= SAVE_DISABLED_MASK;
3442                    }
3443                    break;
3444                case com.android.internal.R.styleable.View_duplicateParentState:
3445                    if (a.getBoolean(attr, false)) {
3446                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3447                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3448                    }
3449                    break;
3450                case com.android.internal.R.styleable.View_visibility:
3451                    final int visibility = a.getInt(attr, 0);
3452                    if (visibility != 0) {
3453                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3454                        viewFlagMasks |= VISIBILITY_MASK;
3455                    }
3456                    break;
3457                case com.android.internal.R.styleable.View_layoutDirection:
3458                    // Clear any layout direction flags (included resolved bits) already set
3459                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3460                    // Set the layout direction flags depending on the value of the attribute
3461                    final int layoutDirection = a.getInt(attr, -1);
3462                    final int value = (layoutDirection != -1) ?
3463                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3464                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3465                    break;
3466                case com.android.internal.R.styleable.View_drawingCacheQuality:
3467                    final int cacheQuality = a.getInt(attr, 0);
3468                    if (cacheQuality != 0) {
3469                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3470                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3471                    }
3472                    break;
3473                case com.android.internal.R.styleable.View_contentDescription:
3474                    setContentDescription(a.getString(attr));
3475                    break;
3476                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3477                    if (!a.getBoolean(attr, true)) {
3478                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3479                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3480                    }
3481                    break;
3482                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3483                    if (!a.getBoolean(attr, true)) {
3484                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3485                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3486                    }
3487                    break;
3488                case R.styleable.View_scrollbars:
3489                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3490                    if (scrollbars != SCROLLBARS_NONE) {
3491                        viewFlagValues |= scrollbars;
3492                        viewFlagMasks |= SCROLLBARS_MASK;
3493                        initializeScrollbars(a);
3494                    }
3495                    break;
3496                //noinspection deprecation
3497                case R.styleable.View_fadingEdge:
3498                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3499                        // Ignore the attribute starting with ICS
3500                        break;
3501                    }
3502                    // With builds < ICS, fall through and apply fading edges
3503                case R.styleable.View_requiresFadingEdge:
3504                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3505                    if (fadingEdge != FADING_EDGE_NONE) {
3506                        viewFlagValues |= fadingEdge;
3507                        viewFlagMasks |= FADING_EDGE_MASK;
3508                        initializeFadingEdge(a);
3509                    }
3510                    break;
3511                case R.styleable.View_scrollbarStyle:
3512                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3513                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3514                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3515                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3516                    }
3517                    break;
3518                case R.styleable.View_isScrollContainer:
3519                    setScrollContainer = true;
3520                    if (a.getBoolean(attr, false)) {
3521                        setScrollContainer(true);
3522                    }
3523                    break;
3524                case com.android.internal.R.styleable.View_keepScreenOn:
3525                    if (a.getBoolean(attr, false)) {
3526                        viewFlagValues |= KEEP_SCREEN_ON;
3527                        viewFlagMasks |= KEEP_SCREEN_ON;
3528                    }
3529                    break;
3530                case R.styleable.View_filterTouchesWhenObscured:
3531                    if (a.getBoolean(attr, false)) {
3532                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3533                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3534                    }
3535                    break;
3536                case R.styleable.View_nextFocusLeft:
3537                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3538                    break;
3539                case R.styleable.View_nextFocusRight:
3540                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3541                    break;
3542                case R.styleable.View_nextFocusUp:
3543                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3544                    break;
3545                case R.styleable.View_nextFocusDown:
3546                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3547                    break;
3548                case R.styleable.View_nextFocusForward:
3549                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3550                    break;
3551                case R.styleable.View_minWidth:
3552                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3553                    break;
3554                case R.styleable.View_minHeight:
3555                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3556                    break;
3557                case R.styleable.View_onClick:
3558                    if (context.isRestricted()) {
3559                        throw new IllegalStateException("The android:onClick attribute cannot "
3560                                + "be used within a restricted context");
3561                    }
3562
3563                    final String handlerName = a.getString(attr);
3564                    if (handlerName != null) {
3565                        setOnClickListener(new OnClickListener() {
3566                            private Method mHandler;
3567
3568                            public void onClick(View v) {
3569                                if (mHandler == null) {
3570                                    try {
3571                                        mHandler = getContext().getClass().getMethod(handlerName,
3572                                                View.class);
3573                                    } catch (NoSuchMethodException e) {
3574                                        int id = getId();
3575                                        String idText = id == NO_ID ? "" : " with id '"
3576                                                + getContext().getResources().getResourceEntryName(
3577                                                    id) + "'";
3578                                        throw new IllegalStateException("Could not find a method " +
3579                                                handlerName + "(View) in the activity "
3580                                                + getContext().getClass() + " for onClick handler"
3581                                                + " on view " + View.this.getClass() + idText, e);
3582                                    }
3583                                }
3584
3585                                try {
3586                                    mHandler.invoke(getContext(), View.this);
3587                                } catch (IllegalAccessException e) {
3588                                    throw new IllegalStateException("Could not execute non "
3589                                            + "public method of the activity", e);
3590                                } catch (InvocationTargetException e) {
3591                                    throw new IllegalStateException("Could not execute "
3592                                            + "method of the activity", e);
3593                                }
3594                            }
3595                        });
3596                    }
3597                    break;
3598                case R.styleable.View_overScrollMode:
3599                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3600                    break;
3601                case R.styleable.View_verticalScrollbarPosition:
3602                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3603                    break;
3604                case R.styleable.View_layerType:
3605                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3606                    break;
3607                case R.styleable.View_textDirection:
3608                    // Clear any text direction flag already set
3609                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3610                    // Set the text direction flags depending on the value of the attribute
3611                    final int textDirection = a.getInt(attr, -1);
3612                    if (textDirection != -1) {
3613                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3614                    }
3615                    break;
3616                case R.styleable.View_textAlignment:
3617                    // Clear any text alignment flag already set
3618                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3619                    // Set the text alignment flag depending on the value of the attribute
3620                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3621                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3622                    break;
3623                case R.styleable.View_importantForAccessibility:
3624                    setImportantForAccessibility(a.getInt(attr,
3625                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3626                    break;
3627            }
3628        }
3629
3630        a.recycle();
3631
3632        setOverScrollMode(overScrollMode);
3633
3634        if (background != null) {
3635            setBackground(background);
3636        }
3637
3638        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3639        // layout direction). Those cached values will be used later during padding resolution.
3640        mUserPaddingStart = startPadding;
3641        mUserPaddingEnd = endPadding;
3642
3643        updateUserPaddingRelative();
3644
3645        if (padding >= 0) {
3646            leftPadding = padding;
3647            topPadding = padding;
3648            rightPadding = padding;
3649            bottomPadding = padding;
3650        }
3651
3652        // If the user specified the padding (either with android:padding or
3653        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3654        // use the default padding or the padding from the background drawable
3655        // (stored at this point in mPadding*)
3656        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3657                topPadding >= 0 ? topPadding : mPaddingTop,
3658                rightPadding >= 0 ? rightPadding : mPaddingRight,
3659                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3660
3661        if (viewFlagMasks != 0) {
3662            setFlags(viewFlagValues, viewFlagMasks);
3663        }
3664
3665        // Needs to be called after mViewFlags is set
3666        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3667            recomputePadding();
3668        }
3669
3670        if (x != 0 || y != 0) {
3671            scrollTo(x, y);
3672        }
3673
3674        if (transformSet) {
3675            setTranslationX(tx);
3676            setTranslationY(ty);
3677            setRotation(rotation);
3678            setRotationX(rotationX);
3679            setRotationY(rotationY);
3680            setScaleX(sx);
3681            setScaleY(sy);
3682        }
3683
3684        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3685            setScrollContainer(true);
3686        }
3687
3688        computeOpaqueFlags();
3689    }
3690
3691    private void updateUserPaddingRelative() {
3692        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3693    }
3694
3695    /**
3696     * Non-public constructor for use in testing
3697     */
3698    View() {
3699        mResources = null;
3700    }
3701
3702    /**
3703     * <p>
3704     * Initializes the fading edges from a given set of styled attributes. This
3705     * method should be called by subclasses that need fading edges and when an
3706     * instance of these subclasses is created programmatically rather than
3707     * being inflated from XML. This method is automatically called when the XML
3708     * is inflated.
3709     * </p>
3710     *
3711     * @param a the styled attributes set to initialize the fading edges from
3712     */
3713    protected void initializeFadingEdge(TypedArray a) {
3714        initScrollCache();
3715
3716        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3717                R.styleable.View_fadingEdgeLength,
3718                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3719    }
3720
3721    /**
3722     * Returns the size of the vertical faded edges used to indicate that more
3723     * content in this view is visible.
3724     *
3725     * @return The size in pixels of the vertical faded edge or 0 if vertical
3726     *         faded edges are not enabled for this view.
3727     * @attr ref android.R.styleable#View_fadingEdgeLength
3728     */
3729    public int getVerticalFadingEdgeLength() {
3730        if (isVerticalFadingEdgeEnabled()) {
3731            ScrollabilityCache cache = mScrollCache;
3732            if (cache != null) {
3733                return cache.fadingEdgeLength;
3734            }
3735        }
3736        return 0;
3737    }
3738
3739    /**
3740     * Set the size of the faded edge used to indicate that more content in this
3741     * view is available.  Will not change whether the fading edge is enabled; use
3742     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3743     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3744     * for the vertical or horizontal fading edges.
3745     *
3746     * @param length The size in pixels of the faded edge used to indicate that more
3747     *        content in this view is visible.
3748     */
3749    public void setFadingEdgeLength(int length) {
3750        initScrollCache();
3751        mScrollCache.fadingEdgeLength = length;
3752    }
3753
3754    /**
3755     * Returns the size of the horizontal faded edges used to indicate that more
3756     * content in this view is visible.
3757     *
3758     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3759     *         faded edges are not enabled for this view.
3760     * @attr ref android.R.styleable#View_fadingEdgeLength
3761     */
3762    public int getHorizontalFadingEdgeLength() {
3763        if (isHorizontalFadingEdgeEnabled()) {
3764            ScrollabilityCache cache = mScrollCache;
3765            if (cache != null) {
3766                return cache.fadingEdgeLength;
3767            }
3768        }
3769        return 0;
3770    }
3771
3772    /**
3773     * Returns the width of the vertical scrollbar.
3774     *
3775     * @return The width in pixels of the vertical scrollbar or 0 if there
3776     *         is no vertical scrollbar.
3777     */
3778    public int getVerticalScrollbarWidth() {
3779        ScrollabilityCache cache = mScrollCache;
3780        if (cache != null) {
3781            ScrollBarDrawable scrollBar = cache.scrollBar;
3782            if (scrollBar != null) {
3783                int size = scrollBar.getSize(true);
3784                if (size <= 0) {
3785                    size = cache.scrollBarSize;
3786                }
3787                return size;
3788            }
3789            return 0;
3790        }
3791        return 0;
3792    }
3793
3794    /**
3795     * Returns the height of the horizontal scrollbar.
3796     *
3797     * @return The height in pixels of the horizontal scrollbar or 0 if
3798     *         there is no horizontal scrollbar.
3799     */
3800    protected int getHorizontalScrollbarHeight() {
3801        ScrollabilityCache cache = mScrollCache;
3802        if (cache != null) {
3803            ScrollBarDrawable scrollBar = cache.scrollBar;
3804            if (scrollBar != null) {
3805                int size = scrollBar.getSize(false);
3806                if (size <= 0) {
3807                    size = cache.scrollBarSize;
3808                }
3809                return size;
3810            }
3811            return 0;
3812        }
3813        return 0;
3814    }
3815
3816    /**
3817     * <p>
3818     * Initializes the scrollbars from a given set of styled attributes. This
3819     * method should be called by subclasses that need scrollbars and when an
3820     * instance of these subclasses is created programmatically rather than
3821     * being inflated from XML. This method is automatically called when the XML
3822     * is inflated.
3823     * </p>
3824     *
3825     * @param a the styled attributes set to initialize the scrollbars from
3826     */
3827    protected void initializeScrollbars(TypedArray a) {
3828        initScrollCache();
3829
3830        final ScrollabilityCache scrollabilityCache = mScrollCache;
3831
3832        if (scrollabilityCache.scrollBar == null) {
3833            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3834        }
3835
3836        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3837
3838        if (!fadeScrollbars) {
3839            scrollabilityCache.state = ScrollabilityCache.ON;
3840        }
3841        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3842
3843
3844        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3845                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3846                        .getScrollBarFadeDuration());
3847        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3848                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3849                ViewConfiguration.getScrollDefaultDelay());
3850
3851
3852        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3853                com.android.internal.R.styleable.View_scrollbarSize,
3854                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3855
3856        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3857        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3858
3859        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3860        if (thumb != null) {
3861            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3862        }
3863
3864        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3865                false);
3866        if (alwaysDraw) {
3867            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3868        }
3869
3870        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3871        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3872
3873        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3874        if (thumb != null) {
3875            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3876        }
3877
3878        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3879                false);
3880        if (alwaysDraw) {
3881            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3882        }
3883
3884        // Re-apply user/background padding so that scrollbar(s) get added
3885        resolvePadding();
3886    }
3887
3888    /**
3889     * <p>
3890     * Initalizes the scrollability cache if necessary.
3891     * </p>
3892     */
3893    private void initScrollCache() {
3894        if (mScrollCache == null) {
3895            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3896        }
3897    }
3898
3899    private ScrollabilityCache getScrollCache() {
3900        initScrollCache();
3901        return mScrollCache;
3902    }
3903
3904    /**
3905     * Set the position of the vertical scroll bar. Should be one of
3906     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3907     * {@link #SCROLLBAR_POSITION_RIGHT}.
3908     *
3909     * @param position Where the vertical scroll bar should be positioned.
3910     */
3911    public void setVerticalScrollbarPosition(int position) {
3912        if (mVerticalScrollbarPosition != position) {
3913            mVerticalScrollbarPosition = position;
3914            computeOpaqueFlags();
3915            resolvePadding();
3916        }
3917    }
3918
3919    /**
3920     * @return The position where the vertical scroll bar will show, if applicable.
3921     * @see #setVerticalScrollbarPosition(int)
3922     */
3923    public int getVerticalScrollbarPosition() {
3924        return mVerticalScrollbarPosition;
3925    }
3926
3927    ListenerInfo getListenerInfo() {
3928        if (mListenerInfo != null) {
3929            return mListenerInfo;
3930        }
3931        mListenerInfo = new ListenerInfo();
3932        return mListenerInfo;
3933    }
3934
3935    /**
3936     * Register a callback to be invoked when focus of this view changed.
3937     *
3938     * @param l The callback that will run.
3939     */
3940    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3941        getListenerInfo().mOnFocusChangeListener = l;
3942    }
3943
3944    /**
3945     * Add a listener that will be called when the bounds of the view change due to
3946     * layout processing.
3947     *
3948     * @param listener The listener that will be called when layout bounds change.
3949     */
3950    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3951        ListenerInfo li = getListenerInfo();
3952        if (li.mOnLayoutChangeListeners == null) {
3953            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3954        }
3955        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3956            li.mOnLayoutChangeListeners.add(listener);
3957        }
3958    }
3959
3960    /**
3961     * Remove a listener for layout changes.
3962     *
3963     * @param listener The listener for layout bounds change.
3964     */
3965    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3966        ListenerInfo li = mListenerInfo;
3967        if (li == null || li.mOnLayoutChangeListeners == null) {
3968            return;
3969        }
3970        li.mOnLayoutChangeListeners.remove(listener);
3971    }
3972
3973    /**
3974     * Add a listener for attach state changes.
3975     *
3976     * This listener will be called whenever this view is attached or detached
3977     * from a window. Remove the listener using
3978     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3979     *
3980     * @param listener Listener to attach
3981     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3982     */
3983    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3984        ListenerInfo li = getListenerInfo();
3985        if (li.mOnAttachStateChangeListeners == null) {
3986            li.mOnAttachStateChangeListeners
3987                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3988        }
3989        li.mOnAttachStateChangeListeners.add(listener);
3990    }
3991
3992    /**
3993     * Remove a listener for attach state changes. The listener will receive no further
3994     * notification of window attach/detach events.
3995     *
3996     * @param listener Listener to remove
3997     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3998     */
3999    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4000        ListenerInfo li = mListenerInfo;
4001        if (li == null || li.mOnAttachStateChangeListeners == null) {
4002            return;
4003        }
4004        li.mOnAttachStateChangeListeners.remove(listener);
4005    }
4006
4007    /**
4008     * Returns the focus-change callback registered for this view.
4009     *
4010     * @return The callback, or null if one is not registered.
4011     */
4012    public OnFocusChangeListener getOnFocusChangeListener() {
4013        ListenerInfo li = mListenerInfo;
4014        return li != null ? li.mOnFocusChangeListener : null;
4015    }
4016
4017    /**
4018     * Register a callback to be invoked when this view is clicked. If this view is not
4019     * clickable, it becomes clickable.
4020     *
4021     * @param l The callback that will run
4022     *
4023     * @see #setClickable(boolean)
4024     */
4025    public void setOnClickListener(OnClickListener l) {
4026        if (!isClickable()) {
4027            setClickable(true);
4028        }
4029        getListenerInfo().mOnClickListener = l;
4030    }
4031
4032    /**
4033     * Return whether this view has an attached OnClickListener.  Returns
4034     * true if there is a listener, false if there is none.
4035     */
4036    public boolean hasOnClickListeners() {
4037        ListenerInfo li = mListenerInfo;
4038        return (li != null && li.mOnClickListener != null);
4039    }
4040
4041    /**
4042     * Register a callback to be invoked when this view is clicked and held. If this view is not
4043     * long clickable, it becomes long clickable.
4044     *
4045     * @param l The callback that will run
4046     *
4047     * @see #setLongClickable(boolean)
4048     */
4049    public void setOnLongClickListener(OnLongClickListener l) {
4050        if (!isLongClickable()) {
4051            setLongClickable(true);
4052        }
4053        getListenerInfo().mOnLongClickListener = l;
4054    }
4055
4056    /**
4057     * Register a callback to be invoked when the context menu for this view is
4058     * being built. If this view is not long clickable, it becomes long clickable.
4059     *
4060     * @param l The callback that will run
4061     *
4062     */
4063    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4064        if (!isLongClickable()) {
4065            setLongClickable(true);
4066        }
4067        getListenerInfo().mOnCreateContextMenuListener = l;
4068    }
4069
4070    /**
4071     * Call this view's OnClickListener, if it is defined.  Performs all normal
4072     * actions associated with clicking: reporting accessibility event, playing
4073     * a sound, etc.
4074     *
4075     * @return True there was an assigned OnClickListener that was called, false
4076     *         otherwise is returned.
4077     */
4078    public boolean performClick() {
4079        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4080
4081        ListenerInfo li = mListenerInfo;
4082        if (li != null && li.mOnClickListener != null) {
4083            playSoundEffect(SoundEffectConstants.CLICK);
4084            li.mOnClickListener.onClick(this);
4085            return true;
4086        }
4087
4088        return false;
4089    }
4090
4091    /**
4092     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4093     * this only calls the listener, and does not do any associated clicking
4094     * actions like reporting an accessibility event.
4095     *
4096     * @return True there was an assigned OnClickListener that was called, false
4097     *         otherwise is returned.
4098     */
4099    public boolean callOnClick() {
4100        ListenerInfo li = mListenerInfo;
4101        if (li != null && li.mOnClickListener != null) {
4102            li.mOnClickListener.onClick(this);
4103            return true;
4104        }
4105        return false;
4106    }
4107
4108    /**
4109     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4110     * OnLongClickListener did not consume the event.
4111     *
4112     * @return True if one of the above receivers consumed the event, false otherwise.
4113     */
4114    public boolean performLongClick() {
4115        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4116
4117        boolean handled = false;
4118        ListenerInfo li = mListenerInfo;
4119        if (li != null && li.mOnLongClickListener != null) {
4120            handled = li.mOnLongClickListener.onLongClick(View.this);
4121        }
4122        if (!handled) {
4123            handled = showContextMenu();
4124        }
4125        if (handled) {
4126            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4127        }
4128        return handled;
4129    }
4130
4131    /**
4132     * Performs button-related actions during a touch down event.
4133     *
4134     * @param event The event.
4135     * @return True if the down was consumed.
4136     *
4137     * @hide
4138     */
4139    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4140        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4141            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4142                return true;
4143            }
4144        }
4145        return false;
4146    }
4147
4148    /**
4149     * Bring up the context menu for this view.
4150     *
4151     * @return Whether a context menu was displayed.
4152     */
4153    public boolean showContextMenu() {
4154        return getParent().showContextMenuForChild(this);
4155    }
4156
4157    /**
4158     * Bring up the context menu for this view, referring to the item under the specified point.
4159     *
4160     * @param x The referenced x coordinate.
4161     * @param y The referenced y coordinate.
4162     * @param metaState The keyboard modifiers that were pressed.
4163     * @return Whether a context menu was displayed.
4164     *
4165     * @hide
4166     */
4167    public boolean showContextMenu(float x, float y, int metaState) {
4168        return showContextMenu();
4169    }
4170
4171    /**
4172     * Start an action mode.
4173     *
4174     * @param callback Callback that will control the lifecycle of the action mode
4175     * @return The new action mode if it is started, null otherwise
4176     *
4177     * @see ActionMode
4178     */
4179    public ActionMode startActionMode(ActionMode.Callback callback) {
4180        ViewParent parent = getParent();
4181        if (parent == null) return null;
4182        return parent.startActionModeForChild(this, callback);
4183    }
4184
4185    /**
4186     * Register a callback to be invoked when a hardware key is pressed in this view.
4187     * Key presses in software input methods will generally not trigger the methods of
4188     * this listener.
4189     * @param l the key listener to attach to this view
4190     */
4191    public void setOnKeyListener(OnKeyListener l) {
4192        getListenerInfo().mOnKeyListener = l;
4193    }
4194
4195    /**
4196     * Register a callback to be invoked when a touch event is sent to this view.
4197     * @param l the touch listener to attach to this view
4198     */
4199    public void setOnTouchListener(OnTouchListener l) {
4200        getListenerInfo().mOnTouchListener = l;
4201    }
4202
4203    /**
4204     * Register a callback to be invoked when a generic motion event is sent to this view.
4205     * @param l the generic motion listener to attach to this view
4206     */
4207    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4208        getListenerInfo().mOnGenericMotionListener = l;
4209    }
4210
4211    /**
4212     * Register a callback to be invoked when a hover event is sent to this view.
4213     * @param l the hover listener to attach to this view
4214     */
4215    public void setOnHoverListener(OnHoverListener l) {
4216        getListenerInfo().mOnHoverListener = l;
4217    }
4218
4219    /**
4220     * Register a drag event listener callback object for this View. The parameter is
4221     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4222     * View, the system calls the
4223     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4224     * @param l An implementation of {@link android.view.View.OnDragListener}.
4225     */
4226    public void setOnDragListener(OnDragListener l) {
4227        getListenerInfo().mOnDragListener = l;
4228    }
4229
4230    /**
4231     * Give this view focus. This will cause
4232     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4233     *
4234     * Note: this does not check whether this {@link View} should get focus, it just
4235     * gives it focus no matter what.  It should only be called internally by framework
4236     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4237     *
4238     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4239     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4240     *        focus moved when requestFocus() is called. It may not always
4241     *        apply, in which case use the default View.FOCUS_DOWN.
4242     * @param previouslyFocusedRect The rectangle of the view that had focus
4243     *        prior in this View's coordinate system.
4244     */
4245    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4246        if (DBG) {
4247            System.out.println(this + " requestFocus()");
4248        }
4249
4250        if ((mPrivateFlags & FOCUSED) == 0) {
4251            mPrivateFlags |= FOCUSED;
4252
4253            if (mParent != null) {
4254                mParent.requestChildFocus(this, this);
4255            }
4256
4257            onFocusChanged(true, direction, previouslyFocusedRect);
4258            refreshDrawableState();
4259
4260            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4261                notifyAccessibilityStateChanged();
4262            }
4263        }
4264    }
4265
4266    /**
4267     * Request that a rectangle of this view be visible on the screen,
4268     * scrolling if necessary just enough.
4269     *
4270     * <p>A View should call this if it maintains some notion of which part
4271     * of its content is interesting.  For example, a text editing view
4272     * should call this when its cursor moves.
4273     *
4274     * @param rectangle The rectangle.
4275     * @return Whether any parent scrolled.
4276     */
4277    public boolean requestRectangleOnScreen(Rect rectangle) {
4278        return requestRectangleOnScreen(rectangle, false);
4279    }
4280
4281    /**
4282     * Request that a rectangle of this view be visible on the screen,
4283     * scrolling if necessary just enough.
4284     *
4285     * <p>A View should call this if it maintains some notion of which part
4286     * of its content is interesting.  For example, a text editing view
4287     * should call this when its cursor moves.
4288     *
4289     * <p>When <code>immediate</code> is set to true, scrolling will not be
4290     * animated.
4291     *
4292     * @param rectangle The rectangle.
4293     * @param immediate True to forbid animated scrolling, false otherwise
4294     * @return Whether any parent scrolled.
4295     */
4296    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4297        View child = this;
4298        ViewParent parent = mParent;
4299        boolean scrolled = false;
4300        while (parent != null) {
4301            scrolled |= parent.requestChildRectangleOnScreen(child,
4302                    rectangle, immediate);
4303
4304            // offset rect so next call has the rectangle in the
4305            // coordinate system of its direct child.
4306            rectangle.offset(child.getLeft(), child.getTop());
4307            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4308
4309            if (!(parent instanceof View)) {
4310                break;
4311            }
4312
4313            child = (View) parent;
4314            parent = child.getParent();
4315        }
4316        return scrolled;
4317    }
4318
4319    /**
4320     * Called when this view wants to give up focus. If focus is cleared
4321     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4322     * <p>
4323     * <strong>Note:</strong> When a View clears focus the framework is trying
4324     * to give focus to the first focusable View from the top. Hence, if this
4325     * View is the first from the top that can take focus, then all callbacks
4326     * related to clearing focus will be invoked after wich the framework will
4327     * give focus to this view.
4328     * </p>
4329     */
4330    public void clearFocus() {
4331        if (DBG) {
4332            System.out.println(this + " clearFocus()");
4333        }
4334
4335        if ((mPrivateFlags & FOCUSED) != 0) {
4336            mPrivateFlags &= ~FOCUSED;
4337
4338            if (mParent != null) {
4339                mParent.clearChildFocus(this);
4340            }
4341
4342            onFocusChanged(false, 0, null);
4343
4344            refreshDrawableState();
4345
4346            ensureInputFocusOnFirstFocusable();
4347
4348            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4349                notifyAccessibilityStateChanged();
4350            }
4351        }
4352    }
4353
4354    void ensureInputFocusOnFirstFocusable() {
4355        View root = getRootView();
4356        if (root != null) {
4357            root.requestFocus();
4358        }
4359    }
4360
4361    /**
4362     * Called internally by the view system when a new view is getting focus.
4363     * This is what clears the old focus.
4364     */
4365    void unFocus() {
4366        if (DBG) {
4367            System.out.println(this + " unFocus()");
4368        }
4369
4370        if ((mPrivateFlags & FOCUSED) != 0) {
4371            mPrivateFlags &= ~FOCUSED;
4372
4373            onFocusChanged(false, 0, null);
4374            refreshDrawableState();
4375
4376            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4377                notifyAccessibilityStateChanged();
4378            }
4379        }
4380    }
4381
4382    /**
4383     * Returns true if this view has focus iteself, or is the ancestor of the
4384     * view that has focus.
4385     *
4386     * @return True if this view has or contains focus, false otherwise.
4387     */
4388    @ViewDebug.ExportedProperty(category = "focus")
4389    public boolean hasFocus() {
4390        return (mPrivateFlags & FOCUSED) != 0;
4391    }
4392
4393    /**
4394     * Returns true if this view is focusable or if it contains a reachable View
4395     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4396     * is a View whose parents do not block descendants focus.
4397     *
4398     * Only {@link #VISIBLE} views are considered focusable.
4399     *
4400     * @return True if the view is focusable or if the view contains a focusable
4401     *         View, false otherwise.
4402     *
4403     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4404     */
4405    public boolean hasFocusable() {
4406        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4407    }
4408
4409    /**
4410     * Called by the view system when the focus state of this view changes.
4411     * When the focus change event is caused by directional navigation, direction
4412     * and previouslyFocusedRect provide insight into where the focus is coming from.
4413     * When overriding, be sure to call up through to the super class so that
4414     * the standard focus handling will occur.
4415     *
4416     * @param gainFocus True if the View has focus; false otherwise.
4417     * @param direction The direction focus has moved when requestFocus()
4418     *                  is called to give this view focus. Values are
4419     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4420     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4421     *                  It may not always apply, in which case use the default.
4422     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4423     *        system, of the previously focused view.  If applicable, this will be
4424     *        passed in as finer grained information about where the focus is coming
4425     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4426     */
4427    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4428        if (gainFocus) {
4429            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4430                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4431            }
4432        }
4433
4434        InputMethodManager imm = InputMethodManager.peekInstance();
4435        if (!gainFocus) {
4436            if (isPressed()) {
4437                setPressed(false);
4438            }
4439            if (imm != null && mAttachInfo != null
4440                    && mAttachInfo.mHasWindowFocus) {
4441                imm.focusOut(this);
4442            }
4443            onFocusLost();
4444        } else if (imm != null && mAttachInfo != null
4445                && mAttachInfo.mHasWindowFocus) {
4446            imm.focusIn(this);
4447        }
4448
4449        invalidate(true);
4450        ListenerInfo li = mListenerInfo;
4451        if (li != null && li.mOnFocusChangeListener != null) {
4452            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4453        }
4454
4455        if (mAttachInfo != null) {
4456            mAttachInfo.mKeyDispatchState.reset(this);
4457        }
4458    }
4459
4460    /**
4461     * Sends an accessibility event of the given type. If accessiiblity is
4462     * not enabled this method has no effect. The default implementation calls
4463     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4464     * to populate information about the event source (this View), then calls
4465     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4466     * populate the text content of the event source including its descendants,
4467     * and last calls
4468     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4469     * on its parent to resuest sending of the event to interested parties.
4470     * <p>
4471     * If an {@link AccessibilityDelegate} has been specified via calling
4472     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4473     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4474     * responsible for handling this call.
4475     * </p>
4476     *
4477     * @param eventType The type of the event to send, as defined by several types from
4478     * {@link android.view.accessibility.AccessibilityEvent}, such as
4479     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4480     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4481     *
4482     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4483     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4484     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4485     * @see AccessibilityDelegate
4486     */
4487    public void sendAccessibilityEvent(int eventType) {
4488        if (mAccessibilityDelegate != null) {
4489            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4490        } else {
4491            sendAccessibilityEventInternal(eventType);
4492        }
4493    }
4494
4495    /**
4496     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4497     * {@link AccessibilityEvent} to make an announcement which is related to some
4498     * sort of a context change for which none of the events representing UI transitions
4499     * is a good fit. For example, announcing a new page in a book. If accessibility
4500     * is not enabled this method does nothing.
4501     *
4502     * @param text The announcement text.
4503     */
4504    public void announceForAccessibility(CharSequence text) {
4505        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4506            AccessibilityEvent event = AccessibilityEvent.obtain(
4507                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4508            event.getText().add(text);
4509            sendAccessibilityEventUnchecked(event);
4510        }
4511    }
4512
4513    /**
4514     * @see #sendAccessibilityEvent(int)
4515     *
4516     * Note: Called from the default {@link AccessibilityDelegate}.
4517     */
4518    void sendAccessibilityEventInternal(int eventType) {
4519        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4520            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4521        }
4522    }
4523
4524    /**
4525     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4526     * takes as an argument an empty {@link AccessibilityEvent} and does not
4527     * perform a check whether accessibility is enabled.
4528     * <p>
4529     * If an {@link AccessibilityDelegate} has been specified via calling
4530     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4531     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4532     * is responsible for handling this call.
4533     * </p>
4534     *
4535     * @param event The event to send.
4536     *
4537     * @see #sendAccessibilityEvent(int)
4538     */
4539    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4540        if (mAccessibilityDelegate != null) {
4541            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4542        } else {
4543            sendAccessibilityEventUncheckedInternal(event);
4544        }
4545    }
4546
4547    /**
4548     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4549     *
4550     * Note: Called from the default {@link AccessibilityDelegate}.
4551     */
4552    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4553        if (!isShown()) {
4554            return;
4555        }
4556        onInitializeAccessibilityEvent(event);
4557        // Only a subset of accessibility events populates text content.
4558        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4559            dispatchPopulateAccessibilityEvent(event);
4560        }
4561        // Intercept accessibility focus events fired by virtual nodes to keep
4562        // track of accessibility focus position in such nodes.
4563        final int eventType = event.getEventType();
4564        switch (eventType) {
4565            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED: {
4566                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4567                        event.getSourceNodeId());
4568                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4569                    ViewRootImpl viewRootImpl = getViewRootImpl();
4570                    if (viewRootImpl != null) {
4571                        viewRootImpl.setAccessibilityFocusedHost(this);
4572                    }
4573                }
4574            } break;
4575            case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED: {
4576                final long virtualNodeId = AccessibilityNodeInfo.getVirtualDescendantId(
4577                        event.getSourceNodeId());
4578                if (virtualNodeId != AccessibilityNodeInfo.UNDEFINED) {
4579                    ViewRootImpl viewRootImpl = getViewRootImpl();
4580                    if (viewRootImpl != null) {
4581                        viewRootImpl.setAccessibilityFocusedHost(null);
4582                    }
4583                }
4584            } break;
4585        }
4586        // In the beginning we called #isShown(), so we know that getParent() is not null.
4587        getParent().requestSendAccessibilityEvent(this, event);
4588    }
4589
4590    /**
4591     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4592     * to its children for adding their text content to the event. Note that the
4593     * event text is populated in a separate dispatch path since we add to the
4594     * event not only the text of the source but also the text of all its descendants.
4595     * A typical implementation will call
4596     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4597     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4598     * on each child. Override this method if custom population of the event text
4599     * content is required.
4600     * <p>
4601     * If an {@link AccessibilityDelegate} has been specified via calling
4602     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4603     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4604     * is responsible for handling this call.
4605     * </p>
4606     * <p>
4607     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4608     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4609     * </p>
4610     *
4611     * @param event The event.
4612     *
4613     * @return True if the event population was completed.
4614     */
4615    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4616        if (mAccessibilityDelegate != null) {
4617            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4618        } else {
4619            return dispatchPopulateAccessibilityEventInternal(event);
4620        }
4621    }
4622
4623    /**
4624     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4625     *
4626     * Note: Called from the default {@link AccessibilityDelegate}.
4627     */
4628    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4629        onPopulateAccessibilityEvent(event);
4630        return false;
4631    }
4632
4633    /**
4634     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4635     * giving a chance to this View to populate the accessibility event with its
4636     * text content. While this method is free to modify event
4637     * attributes other than text content, doing so should normally be performed in
4638     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4639     * <p>
4640     * Example: Adding formatted date string to an accessibility event in addition
4641     *          to the text added by the super implementation:
4642     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4643     *     super.onPopulateAccessibilityEvent(event);
4644     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4645     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4646     *         mCurrentDate.getTimeInMillis(), flags);
4647     *     event.getText().add(selectedDateUtterance);
4648     * }</pre>
4649     * <p>
4650     * If an {@link AccessibilityDelegate} has been specified via calling
4651     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4652     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4653     * is responsible for handling this call.
4654     * </p>
4655     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4656     * information to the event, in case the default implementation has basic information to add.
4657     * </p>
4658     *
4659     * @param event The accessibility event which to populate.
4660     *
4661     * @see #sendAccessibilityEvent(int)
4662     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4663     */
4664    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4665        if (mAccessibilityDelegate != null) {
4666            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4667        } else {
4668            onPopulateAccessibilityEventInternal(event);
4669        }
4670    }
4671
4672    /**
4673     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4674     *
4675     * Note: Called from the default {@link AccessibilityDelegate}.
4676     */
4677    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4678
4679    }
4680
4681    /**
4682     * Initializes an {@link AccessibilityEvent} with information about
4683     * this View which is the event source. In other words, the source of
4684     * an accessibility event is the view whose state change triggered firing
4685     * the event.
4686     * <p>
4687     * Example: Setting the password property of an event in addition
4688     *          to properties set by the super implementation:
4689     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4690     *     super.onInitializeAccessibilityEvent(event);
4691     *     event.setPassword(true);
4692     * }</pre>
4693     * <p>
4694     * If an {@link AccessibilityDelegate} has been specified via calling
4695     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4696     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4697     * is responsible for handling this call.
4698     * </p>
4699     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4700     * information to the event, in case the default implementation has basic information to add.
4701     * </p>
4702     * @param event The event to initialize.
4703     *
4704     * @see #sendAccessibilityEvent(int)
4705     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4706     */
4707    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4708        if (mAccessibilityDelegate != null) {
4709            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4710        } else {
4711            onInitializeAccessibilityEventInternal(event);
4712        }
4713    }
4714
4715    /**
4716     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4717     *
4718     * Note: Called from the default {@link AccessibilityDelegate}.
4719     */
4720    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4721        event.setSource(this);
4722        event.setClassName(View.class.getName());
4723        event.setPackageName(getContext().getPackageName());
4724        event.setEnabled(isEnabled());
4725        event.setContentDescription(mContentDescription);
4726
4727        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4728            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4729            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4730                    FOCUSABLES_ALL);
4731            event.setItemCount(focusablesTempList.size());
4732            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4733            focusablesTempList.clear();
4734        }
4735    }
4736
4737    /**
4738     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4739     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4740     * This method is responsible for obtaining an accessibility node info from a
4741     * pool of reusable instances and calling
4742     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4743     * initialize the former.
4744     * <p>
4745     * Note: The client is responsible for recycling the obtained instance by calling
4746     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4747     * </p>
4748     *
4749     * @return A populated {@link AccessibilityNodeInfo}.
4750     *
4751     * @see AccessibilityNodeInfo
4752     */
4753    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4754        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4755        if (provider != null) {
4756            return provider.createAccessibilityNodeInfo(View.NO_ID);
4757        } else {
4758            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4759            onInitializeAccessibilityNodeInfo(info);
4760            return info;
4761        }
4762    }
4763
4764    /**
4765     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4766     * The base implementation sets:
4767     * <ul>
4768     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4769     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4770     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4771     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4772     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4773     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4774     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4775     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4776     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4777     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4778     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4779     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4780     * </ul>
4781     * <p>
4782     * Subclasses should override this method, call the super implementation,
4783     * and set additional attributes.
4784     * </p>
4785     * <p>
4786     * If an {@link AccessibilityDelegate} has been specified via calling
4787     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4788     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4789     * is responsible for handling this call.
4790     * </p>
4791     *
4792     * @param info The instance to initialize.
4793     */
4794    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4795        if (mAccessibilityDelegate != null) {
4796            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4797        } else {
4798            onInitializeAccessibilityNodeInfoInternal(info);
4799        }
4800    }
4801
4802    /**
4803     * Gets the location of this view in screen coordintates.
4804     *
4805     * @param outRect The output location
4806     */
4807    private void getBoundsOnScreen(Rect outRect) {
4808        if (mAttachInfo == null) {
4809            return;
4810        }
4811
4812        RectF position = mAttachInfo.mTmpTransformRect;
4813        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4814
4815        if (!hasIdentityMatrix()) {
4816            getMatrix().mapRect(position);
4817        }
4818
4819        position.offset(mLeft, mTop);
4820
4821        ViewParent parent = mParent;
4822        while (parent instanceof View) {
4823            View parentView = (View) parent;
4824
4825            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4826
4827            if (!parentView.hasIdentityMatrix()) {
4828                parentView.getMatrix().mapRect(position);
4829            }
4830
4831            position.offset(parentView.mLeft, parentView.mTop);
4832
4833            parent = parentView.mParent;
4834        }
4835
4836        if (parent instanceof ViewRootImpl) {
4837            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4838            position.offset(0, -viewRootImpl.mCurScrollY);
4839        }
4840
4841        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4842
4843        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4844                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4845    }
4846
4847    /**
4848     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4849     *
4850     * Note: Called from the default {@link AccessibilityDelegate}.
4851     */
4852    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4853        Rect bounds = mAttachInfo.mTmpInvalRect;
4854        getDrawingRect(bounds);
4855        info.setBoundsInParent(bounds);
4856
4857        getBoundsOnScreen(bounds);
4858        info.setBoundsInScreen(bounds);
4859
4860        ViewParent parent = getParentForAccessibility();
4861        if (parent instanceof View) {
4862            info.setParent((View) parent);
4863        }
4864
4865        info.setVisibleToUser(isVisibleToUser());
4866
4867        info.setPackageName(mContext.getPackageName());
4868        info.setClassName(View.class.getName());
4869        info.setContentDescription(getContentDescription());
4870
4871        info.setEnabled(isEnabled());
4872        info.setClickable(isClickable());
4873        info.setFocusable(isFocusable());
4874        info.setFocused(isFocused());
4875        info.setAccessibilityFocused(isAccessibilityFocused());
4876        info.setSelected(isSelected());
4877        info.setLongClickable(isLongClickable());
4878
4879        // TODO: These make sense only if we are in an AdapterView but all
4880        // views can be selected. Maybe from accessiiblity perspective
4881        // we should report as selectable view in an AdapterView.
4882        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4883        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4884
4885        if (isFocusable()) {
4886            if (isFocused()) {
4887                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4888            } else {
4889                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4890            }
4891        }
4892
4893        if (!isAccessibilityFocused()) {
4894            final int mode = getAccessibilityFocusable();
4895            if (mode == ACCESSIBILITY_FOCUSABLE_YES || mode == ACCESSIBILITY_FOCUSABLE_AUTO) {
4896                info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4897            }
4898        } else {
4899            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4900        }
4901
4902        if (isClickable() && isEnabled()) {
4903            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4904        }
4905
4906        if (isLongClickable() && isEnabled()) {
4907            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4908        }
4909
4910        if (mContentDescription != null && mContentDescription.length() > 0) {
4911            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4912            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4913            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4914                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4915                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4916        }
4917    }
4918
4919    /**
4920     * Returns the delta between the actual and last reported window left.
4921     *
4922     * @hide
4923     */
4924    public int getActualAndReportedWindowLeftDelta() {
4925        if (mAttachInfo != null) {
4926            return mAttachInfo.mActualWindowLeft - mAttachInfo.mWindowLeft;
4927        }
4928        return 0;
4929    }
4930
4931    /**
4932     * Returns the delta between the actual and last reported window top.
4933     *
4934     * @hide
4935     */
4936    public int getActualAndReportedWindowTopDelta() {
4937        if (mAttachInfo != null) {
4938            return mAttachInfo.mActualWindowTop - mAttachInfo.mWindowTop;
4939        }
4940        return 0;
4941    }
4942
4943    /**
4944     * Computes whether this view is visible to the user. Such a view is
4945     * attached, visible, all its predecessors are visible, it is not clipped
4946     * entirely by its predecessors, and has an alpha greater than zero.
4947     *
4948     * @return Whether the view is visible on the screen.
4949     *
4950     * @hide
4951     */
4952    protected boolean isVisibleToUser() {
4953        return isVisibleToUser(null);
4954    }
4955
4956    /**
4957     * Computes whether the given portion of this view is visible to the user. Such a view is
4958     * attached, visible, all its predecessors are visible, has an alpha greater than zero, and
4959     * the specified portion is not clipped entirely by its predecessors.
4960     *
4961     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4962     *                    <code>null</code>, and the entire view will be tested in this case.
4963     *                    When <code>true</code> is returned by the function, the actual visible
4964     *                    region will be stored in this parameter; that is, if boundInView is fully
4965     *                    contained within the view, no modification will be made, otherwise regions
4966     *                    outside of the visible area of the view will be clipped.
4967     *
4968     * @return Whether the specified portion of the view is visible on the screen.
4969     *
4970     * @hide
4971     */
4972    protected boolean isVisibleToUser(Rect boundInView) {
4973        Rect visibleRect = mAttachInfo.mTmpInvalRect;
4974        Point offset = mAttachInfo.mPoint;
4975        // The first two checks are made also made by isShown() which
4976        // however traverses the tree up to the parent to catch that.
4977        // Therefore, we do some fail fast check to minimize the up
4978        // tree traversal.
4979        boolean isVisible = mAttachInfo != null
4980            && mAttachInfo.mWindowVisibility == View.VISIBLE
4981            && getAlpha() > 0
4982            && isShown()
4983            && getGlobalVisibleRect(visibleRect, offset);
4984            if (isVisible && boundInView != null) {
4985                visibleRect.offset(-offset.x, -offset.y);
4986                isVisible &= boundInView.intersect(visibleRect);
4987            }
4988            return isVisible;
4989    }
4990
4991    /**
4992     * Sets a delegate for implementing accessibility support via compositon as
4993     * opposed to inheritance. The delegate's primary use is for implementing
4994     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4995     *
4996     * @param delegate The delegate instance.
4997     *
4998     * @see AccessibilityDelegate
4999     */
5000    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5001        mAccessibilityDelegate = delegate;
5002    }
5003
5004    /**
5005     * Gets the provider for managing a virtual view hierarchy rooted at this View
5006     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5007     * that explore the window content.
5008     * <p>
5009     * If this method returns an instance, this instance is responsible for managing
5010     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5011     * View including the one representing the View itself. Similarly the returned
5012     * instance is responsible for performing accessibility actions on any virtual
5013     * view or the root view itself.
5014     * </p>
5015     * <p>
5016     * If an {@link AccessibilityDelegate} has been specified via calling
5017     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5018     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5019     * is responsible for handling this call.
5020     * </p>
5021     *
5022     * @return The provider.
5023     *
5024     * @see AccessibilityNodeProvider
5025     */
5026    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5027        if (mAccessibilityDelegate != null) {
5028            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5029        } else {
5030            return null;
5031        }
5032    }
5033
5034    /**
5035     * Gets the unique identifier of this view on the screen for accessibility purposes.
5036     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5037     *
5038     * @return The view accessibility id.
5039     *
5040     * @hide
5041     */
5042    public int getAccessibilityViewId() {
5043        if (mAccessibilityViewId == NO_ID) {
5044            mAccessibilityViewId = sNextAccessibilityViewId++;
5045        }
5046        return mAccessibilityViewId;
5047    }
5048
5049    /**
5050     * Gets the unique identifier of the window in which this View reseides.
5051     *
5052     * @return The window accessibility id.
5053     *
5054     * @hide
5055     */
5056    public int getAccessibilityWindowId() {
5057        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5058    }
5059
5060    /**
5061     * Gets the {@link View} description. It briefly describes the view and is
5062     * primarily used for accessibility support. Set this property to enable
5063     * better accessibility support for your application. This is especially
5064     * true for views that do not have textual representation (For example,
5065     * ImageButton).
5066     *
5067     * @return The content description.
5068     *
5069     * @attr ref android.R.styleable#View_contentDescription
5070     */
5071    @ViewDebug.ExportedProperty(category = "accessibility")
5072    public CharSequence getContentDescription() {
5073        return mContentDescription;
5074    }
5075
5076    /**
5077     * Sets the {@link View} description. It briefly describes the view and is
5078     * primarily used for accessibility support. Set this property to enable
5079     * better accessibility support for your application. This is especially
5080     * true for views that do not have textual representation (For example,
5081     * ImageButton).
5082     *
5083     * @param contentDescription The content description.
5084     *
5085     * @attr ref android.R.styleable#View_contentDescription
5086     */
5087    @RemotableViewMethod
5088    public void setContentDescription(CharSequence contentDescription) {
5089        mContentDescription = contentDescription;
5090        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5091        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5092             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5093        }
5094    }
5095
5096    /**
5097     * Invoked whenever this view loses focus, either by losing window focus or by losing
5098     * focus within its window. This method can be used to clear any state tied to the
5099     * focus. For instance, if a button is held pressed with the trackball and the window
5100     * loses focus, this method can be used to cancel the press.
5101     *
5102     * Subclasses of View overriding this method should always call super.onFocusLost().
5103     *
5104     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5105     * @see #onWindowFocusChanged(boolean)
5106     *
5107     * @hide pending API council approval
5108     */
5109    protected void onFocusLost() {
5110        resetPressedState();
5111    }
5112
5113    private void resetPressedState() {
5114        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5115            return;
5116        }
5117
5118        if (isPressed()) {
5119            setPressed(false);
5120
5121            if (!mHasPerformedLongPress) {
5122                removeLongPressCallback();
5123            }
5124        }
5125    }
5126
5127    /**
5128     * Returns true if this view has focus
5129     *
5130     * @return True if this view has focus, false otherwise.
5131     */
5132    @ViewDebug.ExportedProperty(category = "focus")
5133    public boolean isFocused() {
5134        return (mPrivateFlags & FOCUSED) != 0;
5135    }
5136
5137    /**
5138     * Find the view in the hierarchy rooted at this view that currently has
5139     * focus.
5140     *
5141     * @return The view that currently has focus, or null if no focused view can
5142     *         be found.
5143     */
5144    public View findFocus() {
5145        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
5146    }
5147
5148    /**
5149     * Indicates whether this view is one of the set of scrollable containers in
5150     * its window.
5151     *
5152     * @return whether this view is one of the set of scrollable containers in
5153     * its window
5154     *
5155     * @attr ref android.R.styleable#View_isScrollContainer
5156     */
5157    public boolean isScrollContainer() {
5158        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
5159    }
5160
5161    /**
5162     * Change whether this view is one of the set of scrollable containers in
5163     * its window.  This will be used to determine whether the window can
5164     * resize or must pan when a soft input area is open -- scrollable
5165     * containers allow the window to use resize mode since the container
5166     * will appropriately shrink.
5167     *
5168     * @attr ref android.R.styleable#View_isScrollContainer
5169     */
5170    public void setScrollContainer(boolean isScrollContainer) {
5171        if (isScrollContainer) {
5172            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5173                mAttachInfo.mScrollContainers.add(this);
5174                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5175            }
5176            mPrivateFlags |= SCROLL_CONTAINER;
5177        } else {
5178            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5179                mAttachInfo.mScrollContainers.remove(this);
5180            }
5181            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5182        }
5183    }
5184
5185    /**
5186     * Returns the quality of the drawing cache.
5187     *
5188     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5189     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5190     *
5191     * @see #setDrawingCacheQuality(int)
5192     * @see #setDrawingCacheEnabled(boolean)
5193     * @see #isDrawingCacheEnabled()
5194     *
5195     * @attr ref android.R.styleable#View_drawingCacheQuality
5196     */
5197    public int getDrawingCacheQuality() {
5198        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5199    }
5200
5201    /**
5202     * Set the drawing cache quality of this view. This value is used only when the
5203     * drawing cache is enabled
5204     *
5205     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5206     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5207     *
5208     * @see #getDrawingCacheQuality()
5209     * @see #setDrawingCacheEnabled(boolean)
5210     * @see #isDrawingCacheEnabled()
5211     *
5212     * @attr ref android.R.styleable#View_drawingCacheQuality
5213     */
5214    public void setDrawingCacheQuality(int quality) {
5215        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5216    }
5217
5218    /**
5219     * Returns whether the screen should remain on, corresponding to the current
5220     * value of {@link #KEEP_SCREEN_ON}.
5221     *
5222     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5223     *
5224     * @see #setKeepScreenOn(boolean)
5225     *
5226     * @attr ref android.R.styleable#View_keepScreenOn
5227     */
5228    public boolean getKeepScreenOn() {
5229        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5230    }
5231
5232    /**
5233     * Controls whether the screen should remain on, modifying the
5234     * value of {@link #KEEP_SCREEN_ON}.
5235     *
5236     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5237     *
5238     * @see #getKeepScreenOn()
5239     *
5240     * @attr ref android.R.styleable#View_keepScreenOn
5241     */
5242    public void setKeepScreenOn(boolean keepScreenOn) {
5243        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5244    }
5245
5246    /**
5247     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5248     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5249     *
5250     * @attr ref android.R.styleable#View_nextFocusLeft
5251     */
5252    public int getNextFocusLeftId() {
5253        return mNextFocusLeftId;
5254    }
5255
5256    /**
5257     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5258     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5259     * decide automatically.
5260     *
5261     * @attr ref android.R.styleable#View_nextFocusLeft
5262     */
5263    public void setNextFocusLeftId(int nextFocusLeftId) {
5264        mNextFocusLeftId = nextFocusLeftId;
5265    }
5266
5267    /**
5268     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5269     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5270     *
5271     * @attr ref android.R.styleable#View_nextFocusRight
5272     */
5273    public int getNextFocusRightId() {
5274        return mNextFocusRightId;
5275    }
5276
5277    /**
5278     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5279     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5280     * decide automatically.
5281     *
5282     * @attr ref android.R.styleable#View_nextFocusRight
5283     */
5284    public void setNextFocusRightId(int nextFocusRightId) {
5285        mNextFocusRightId = nextFocusRightId;
5286    }
5287
5288    /**
5289     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5290     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5291     *
5292     * @attr ref android.R.styleable#View_nextFocusUp
5293     */
5294    public int getNextFocusUpId() {
5295        return mNextFocusUpId;
5296    }
5297
5298    /**
5299     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5300     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5301     * decide automatically.
5302     *
5303     * @attr ref android.R.styleable#View_nextFocusUp
5304     */
5305    public void setNextFocusUpId(int nextFocusUpId) {
5306        mNextFocusUpId = nextFocusUpId;
5307    }
5308
5309    /**
5310     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5311     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5312     *
5313     * @attr ref android.R.styleable#View_nextFocusDown
5314     */
5315    public int getNextFocusDownId() {
5316        return mNextFocusDownId;
5317    }
5318
5319    /**
5320     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5321     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5322     * decide automatically.
5323     *
5324     * @attr ref android.R.styleable#View_nextFocusDown
5325     */
5326    public void setNextFocusDownId(int nextFocusDownId) {
5327        mNextFocusDownId = nextFocusDownId;
5328    }
5329
5330    /**
5331     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5332     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5333     *
5334     * @attr ref android.R.styleable#View_nextFocusForward
5335     */
5336    public int getNextFocusForwardId() {
5337        return mNextFocusForwardId;
5338    }
5339
5340    /**
5341     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5342     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5343     * decide automatically.
5344     *
5345     * @attr ref android.R.styleable#View_nextFocusForward
5346     */
5347    public void setNextFocusForwardId(int nextFocusForwardId) {
5348        mNextFocusForwardId = nextFocusForwardId;
5349    }
5350
5351    /**
5352     * Returns the visibility of this view and all of its ancestors
5353     *
5354     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5355     */
5356    public boolean isShown() {
5357        View current = this;
5358        //noinspection ConstantConditions
5359        do {
5360            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5361                return false;
5362            }
5363            ViewParent parent = current.mParent;
5364            if (parent == null) {
5365                return false; // We are not attached to the view root
5366            }
5367            if (!(parent instanceof View)) {
5368                return true;
5369            }
5370            current = (View) parent;
5371        } while (current != null);
5372
5373        return false;
5374    }
5375
5376    /**
5377     * Called by the view hierarchy when the content insets for a window have
5378     * changed, to allow it to adjust its content to fit within those windows.
5379     * The content insets tell you the space that the status bar, input method,
5380     * and other system windows infringe on the application's window.
5381     *
5382     * <p>You do not normally need to deal with this function, since the default
5383     * window decoration given to applications takes care of applying it to the
5384     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5385     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5386     * and your content can be placed under those system elements.  You can then
5387     * use this method within your view hierarchy if you have parts of your UI
5388     * which you would like to ensure are not being covered.
5389     *
5390     * <p>The default implementation of this method simply applies the content
5391     * inset's to the view's padding, consuming that content (modifying the
5392     * insets to be 0), and returning true.  This behavior is off by default, but can
5393     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5394     *
5395     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5396     * insets object is propagated down the hierarchy, so any changes made to it will
5397     * be seen by all following views (including potentially ones above in
5398     * the hierarchy since this is a depth-first traversal).  The first view
5399     * that returns true will abort the entire traversal.
5400     *
5401     * <p>The default implementation works well for a situation where it is
5402     * used with a container that covers the entire window, allowing it to
5403     * apply the appropriate insets to its content on all edges.  If you need
5404     * a more complicated layout (such as two different views fitting system
5405     * windows, one on the top of the window, and one on the bottom),
5406     * you can override the method and handle the insets however you would like.
5407     * Note that the insets provided by the framework are always relative to the
5408     * far edges of the window, not accounting for the location of the called view
5409     * within that window.  (In fact when this method is called you do not yet know
5410     * where the layout will place the view, as it is done before layout happens.)
5411     *
5412     * <p>Note: unlike many View methods, there is no dispatch phase to this
5413     * call.  If you are overriding it in a ViewGroup and want to allow the
5414     * call to continue to your children, you must be sure to call the super
5415     * implementation.
5416     *
5417     * <p>Here is a sample layout that makes use of fitting system windows
5418     * to have controls for a video view placed inside of the window decorations
5419     * that it hides and shows.  This can be used with code like the second
5420     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5421     *
5422     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5423     *
5424     * @param insets Current content insets of the window.  Prior to
5425     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5426     * the insets or else you and Android will be unhappy.
5427     *
5428     * @return Return true if this view applied the insets and it should not
5429     * continue propagating further down the hierarchy, false otherwise.
5430     * @see #getFitsSystemWindows()
5431     * @see #setFitsSystemWindows()
5432     * @see #setSystemUiVisibility(int)
5433     */
5434    protected boolean fitSystemWindows(Rect insets) {
5435        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5436            mUserPaddingStart = -1;
5437            mUserPaddingEnd = -1;
5438            mUserPaddingRelative = false;
5439            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5440                    || mAttachInfo == null
5441                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5442                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5443                return true;
5444            } else {
5445                internalSetPadding(0, 0, 0, 0);
5446                return false;
5447            }
5448        }
5449        return false;
5450    }
5451
5452    /**
5453     * Sets whether or not this view should account for system screen decorations
5454     * such as the status bar and inset its content; that is, controlling whether
5455     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5456     * executed.  See that method for more details.
5457     *
5458     * <p>Note that if you are providing your own implementation of
5459     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5460     * flag to true -- your implementation will be overriding the default
5461     * implementation that checks this flag.
5462     *
5463     * @param fitSystemWindows If true, then the default implementation of
5464     * {@link #fitSystemWindows(Rect)} will be executed.
5465     *
5466     * @attr ref android.R.styleable#View_fitsSystemWindows
5467     * @see #getFitsSystemWindows()
5468     * @see #fitSystemWindows(Rect)
5469     * @see #setSystemUiVisibility(int)
5470     */
5471    public void setFitsSystemWindows(boolean fitSystemWindows) {
5472        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5473    }
5474
5475    /**
5476     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5477     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5478     * will be executed.
5479     *
5480     * @return Returns true if the default implementation of
5481     * {@link #fitSystemWindows(Rect)} will be executed.
5482     *
5483     * @attr ref android.R.styleable#View_fitsSystemWindows
5484     * @see #setFitsSystemWindows()
5485     * @see #fitSystemWindows(Rect)
5486     * @see #setSystemUiVisibility(int)
5487     */
5488    public boolean getFitsSystemWindows() {
5489        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5490    }
5491
5492    /** @hide */
5493    public boolean fitsSystemWindows() {
5494        return getFitsSystemWindows();
5495    }
5496
5497    /**
5498     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5499     */
5500    public void requestFitSystemWindows() {
5501        if (mParent != null) {
5502            mParent.requestFitSystemWindows();
5503        }
5504    }
5505
5506    /**
5507     * For use by PhoneWindow to make its own system window fitting optional.
5508     * @hide
5509     */
5510    public void makeOptionalFitsSystemWindows() {
5511        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5512    }
5513
5514    /**
5515     * Returns the visibility status for this view.
5516     *
5517     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5518     * @attr ref android.R.styleable#View_visibility
5519     */
5520    @ViewDebug.ExportedProperty(mapping = {
5521        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5522        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5523        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5524    })
5525    public int getVisibility() {
5526        return mViewFlags & VISIBILITY_MASK;
5527    }
5528
5529    /**
5530     * Set the enabled state of this view.
5531     *
5532     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5533     * @attr ref android.R.styleable#View_visibility
5534     */
5535    @RemotableViewMethod
5536    public void setVisibility(int visibility) {
5537        setFlags(visibility, VISIBILITY_MASK);
5538        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5539    }
5540
5541    /**
5542     * Returns the enabled status for this view. The interpretation of the
5543     * enabled state varies by subclass.
5544     *
5545     * @return True if this view is enabled, false otherwise.
5546     */
5547    @ViewDebug.ExportedProperty
5548    public boolean isEnabled() {
5549        return (mViewFlags & ENABLED_MASK) == ENABLED;
5550    }
5551
5552    /**
5553     * Set the enabled state of this view. The interpretation of the enabled
5554     * state varies by subclass.
5555     *
5556     * @param enabled True if this view is enabled, false otherwise.
5557     */
5558    @RemotableViewMethod
5559    public void setEnabled(boolean enabled) {
5560        if (enabled == isEnabled()) return;
5561
5562        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5563
5564        /*
5565         * The View most likely has to change its appearance, so refresh
5566         * the drawable state.
5567         */
5568        refreshDrawableState();
5569
5570        // Invalidate too, since the default behavior for views is to be
5571        // be drawn at 50% alpha rather than to change the drawable.
5572        invalidate(true);
5573    }
5574
5575    /**
5576     * Set whether this view can receive the focus.
5577     *
5578     * Setting this to false will also ensure that this view is not focusable
5579     * in touch mode.
5580     *
5581     * @param focusable If true, this view can receive the focus.
5582     *
5583     * @see #setFocusableInTouchMode(boolean)
5584     * @attr ref android.R.styleable#View_focusable
5585     */
5586    public void setFocusable(boolean focusable) {
5587        if (!focusable) {
5588            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5589        }
5590        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5591    }
5592
5593    /**
5594     * Set whether this view can receive focus while in touch mode.
5595     *
5596     * Setting this to true will also ensure that this view is focusable.
5597     *
5598     * @param focusableInTouchMode If true, this view can receive the focus while
5599     *   in touch mode.
5600     *
5601     * @see #setFocusable(boolean)
5602     * @attr ref android.R.styleable#View_focusableInTouchMode
5603     */
5604    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5605        // Focusable in touch mode should always be set before the focusable flag
5606        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5607        // which, in touch mode, will not successfully request focus on this view
5608        // because the focusable in touch mode flag is not set
5609        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5610        if (focusableInTouchMode) {
5611            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5612        }
5613    }
5614
5615    /**
5616     * Set whether this view should have sound effects enabled for events such as
5617     * clicking and touching.
5618     *
5619     * <p>You may wish to disable sound effects for a view if you already play sounds,
5620     * for instance, a dial key that plays dtmf tones.
5621     *
5622     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5623     * @see #isSoundEffectsEnabled()
5624     * @see #playSoundEffect(int)
5625     * @attr ref android.R.styleable#View_soundEffectsEnabled
5626     */
5627    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5628        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5629    }
5630
5631    /**
5632     * @return whether this view should have sound effects enabled for events such as
5633     *     clicking and touching.
5634     *
5635     * @see #setSoundEffectsEnabled(boolean)
5636     * @see #playSoundEffect(int)
5637     * @attr ref android.R.styleable#View_soundEffectsEnabled
5638     */
5639    @ViewDebug.ExportedProperty
5640    public boolean isSoundEffectsEnabled() {
5641        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5642    }
5643
5644    /**
5645     * Set whether this view should have haptic feedback for events such as
5646     * long presses.
5647     *
5648     * <p>You may wish to disable haptic feedback if your view already controls
5649     * its own haptic feedback.
5650     *
5651     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5652     * @see #isHapticFeedbackEnabled()
5653     * @see #performHapticFeedback(int)
5654     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5655     */
5656    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5657        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5658    }
5659
5660    /**
5661     * @return whether this view should have haptic feedback enabled for events
5662     * long presses.
5663     *
5664     * @see #setHapticFeedbackEnabled(boolean)
5665     * @see #performHapticFeedback(int)
5666     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5667     */
5668    @ViewDebug.ExportedProperty
5669    public boolean isHapticFeedbackEnabled() {
5670        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5671    }
5672
5673    /**
5674     * Returns the layout direction for this view.
5675     *
5676     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5677     *   {@link #LAYOUT_DIRECTION_RTL},
5678     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5679     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5680     *
5681     * @attr ref android.R.styleable#View_layoutDirection
5682     * @hide
5683     */
5684    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5685        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5686        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5687        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5688        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5689    })
5690    public int getLayoutDirection() {
5691        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5692    }
5693
5694    /**
5695     * Set the layout direction for this view. This will propagate a reset of layout direction
5696     * resolution to the view's children and resolve layout direction for this view.
5697     *
5698     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5699     *   {@link #LAYOUT_DIRECTION_RTL},
5700     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5701     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5702     *
5703     * @attr ref android.R.styleable#View_layoutDirection
5704     * @hide
5705     */
5706    @RemotableViewMethod
5707    public void setLayoutDirection(int layoutDirection) {
5708        if (getLayoutDirection() != layoutDirection) {
5709            // Reset the current layout direction and the resolved one
5710            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5711            resetResolvedLayoutDirection();
5712            // Set the new layout direction (filtered) and ask for a layout pass
5713            mPrivateFlags2 |=
5714                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5715            requestLayout();
5716        }
5717    }
5718
5719    /**
5720     * Returns the resolved layout direction for this view.
5721     *
5722     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5723     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5724     * @hide
5725     */
5726    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5727        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5728        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5729    })
5730    public int getResolvedLayoutDirection() {
5731        // The layout diretion will be resolved only if needed
5732        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5733            resolveLayoutDirection();
5734        }
5735        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5736                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5737    }
5738
5739    /**
5740     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5741     * layout attribute and/or the inherited value from the parent
5742     *
5743     * @return true if the layout is right-to-left.
5744     * @hide
5745     */
5746    @ViewDebug.ExportedProperty(category = "layout")
5747    public boolean isLayoutRtl() {
5748        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5749    }
5750
5751    /**
5752     * Indicates whether the view is currently tracking transient state that the
5753     * app should not need to concern itself with saving and restoring, but that
5754     * the framework should take special note to preserve when possible.
5755     *
5756     * <p>A view with transient state cannot be trivially rebound from an external
5757     * data source, such as an adapter binding item views in a list. This may be
5758     * because the view is performing an animation, tracking user selection
5759     * of content, or similar.</p>
5760     *
5761     * @return true if the view has transient state
5762     */
5763    @ViewDebug.ExportedProperty(category = "layout")
5764    public boolean hasTransientState() {
5765        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5766    }
5767
5768    /**
5769     * Set whether this view is currently tracking transient state that the
5770     * framework should attempt to preserve when possible. This flag is reference counted,
5771     * so every call to setHasTransientState(true) should be paired with a later call
5772     * to setHasTransientState(false).
5773     *
5774     * <p>A view with transient state cannot be trivially rebound from an external
5775     * data source, such as an adapter binding item views in a list. This may be
5776     * because the view is performing an animation, tracking user selection
5777     * of content, or similar.</p>
5778     *
5779     * @param hasTransientState true if this view has transient state
5780     */
5781    public void setHasTransientState(boolean hasTransientState) {
5782        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5783                mTransientStateCount - 1;
5784        if (mTransientStateCount < 0) {
5785            mTransientStateCount = 0;
5786            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5787                    "unmatched pair of setHasTransientState calls");
5788        }
5789        if ((hasTransientState && mTransientStateCount == 1) ||
5790                (!hasTransientState && mTransientStateCount == 0)) {
5791            // update flag if we've just incremented up from 0 or decremented down to 0
5792            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5793                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5794            if (mParent != null) {
5795                try {
5796                    mParent.childHasTransientStateChanged(this, hasTransientState);
5797                } catch (AbstractMethodError e) {
5798                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5799                            " does not fully implement ViewParent", e);
5800                }
5801            }
5802        }
5803    }
5804
5805    /**
5806     * If this view doesn't do any drawing on its own, set this flag to
5807     * allow further optimizations. By default, this flag is not set on
5808     * View, but could be set on some View subclasses such as ViewGroup.
5809     *
5810     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5811     * you should clear this flag.
5812     *
5813     * @param willNotDraw whether or not this View draw on its own
5814     */
5815    public void setWillNotDraw(boolean willNotDraw) {
5816        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5817    }
5818
5819    /**
5820     * Returns whether or not this View draws on its own.
5821     *
5822     * @return true if this view has nothing to draw, false otherwise
5823     */
5824    @ViewDebug.ExportedProperty(category = "drawing")
5825    public boolean willNotDraw() {
5826        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5827    }
5828
5829    /**
5830     * When a View's drawing cache is enabled, drawing is redirected to an
5831     * offscreen bitmap. Some views, like an ImageView, must be able to
5832     * bypass this mechanism if they already draw a single bitmap, to avoid
5833     * unnecessary usage of the memory.
5834     *
5835     * @param willNotCacheDrawing true if this view does not cache its
5836     *        drawing, false otherwise
5837     */
5838    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5839        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5840    }
5841
5842    /**
5843     * Returns whether or not this View can cache its drawing or not.
5844     *
5845     * @return true if this view does not cache its drawing, false otherwise
5846     */
5847    @ViewDebug.ExportedProperty(category = "drawing")
5848    public boolean willNotCacheDrawing() {
5849        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5850    }
5851
5852    /**
5853     * Indicates whether this view reacts to click events or not.
5854     *
5855     * @return true if the view is clickable, false otherwise
5856     *
5857     * @see #setClickable(boolean)
5858     * @attr ref android.R.styleable#View_clickable
5859     */
5860    @ViewDebug.ExportedProperty
5861    public boolean isClickable() {
5862        return (mViewFlags & CLICKABLE) == CLICKABLE;
5863    }
5864
5865    /**
5866     * Enables or disables click events for this view. When a view
5867     * is clickable it will change its state to "pressed" on every click.
5868     * Subclasses should set the view clickable to visually react to
5869     * user's clicks.
5870     *
5871     * @param clickable true to make the view clickable, false otherwise
5872     *
5873     * @see #isClickable()
5874     * @attr ref android.R.styleable#View_clickable
5875     */
5876    public void setClickable(boolean clickable) {
5877        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5878    }
5879
5880    /**
5881     * Indicates whether this view reacts to long click events or not.
5882     *
5883     * @return true if the view is long clickable, false otherwise
5884     *
5885     * @see #setLongClickable(boolean)
5886     * @attr ref android.R.styleable#View_longClickable
5887     */
5888    public boolean isLongClickable() {
5889        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5890    }
5891
5892    /**
5893     * Enables or disables long click events for this view. When a view is long
5894     * clickable it reacts to the user holding down the button for a longer
5895     * duration than a tap. This event can either launch the listener or a
5896     * context menu.
5897     *
5898     * @param longClickable true to make the view long clickable, false otherwise
5899     * @see #isLongClickable()
5900     * @attr ref android.R.styleable#View_longClickable
5901     */
5902    public void setLongClickable(boolean longClickable) {
5903        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5904    }
5905
5906    /**
5907     * Sets the pressed state for this view.
5908     *
5909     * @see #isClickable()
5910     * @see #setClickable(boolean)
5911     *
5912     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5913     *        the View's internal state from a previously set "pressed" state.
5914     */
5915    public void setPressed(boolean pressed) {
5916        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5917
5918        if (pressed) {
5919            mPrivateFlags |= PRESSED;
5920        } else {
5921            mPrivateFlags &= ~PRESSED;
5922        }
5923
5924        if (needsRefresh) {
5925            refreshDrawableState();
5926        }
5927        dispatchSetPressed(pressed);
5928    }
5929
5930    /**
5931     * Dispatch setPressed to all of this View's children.
5932     *
5933     * @see #setPressed(boolean)
5934     *
5935     * @param pressed The new pressed state
5936     */
5937    protected void dispatchSetPressed(boolean pressed) {
5938    }
5939
5940    /**
5941     * Indicates whether the view is currently in pressed state. Unless
5942     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5943     * the pressed state.
5944     *
5945     * @see #setPressed(boolean)
5946     * @see #isClickable()
5947     * @see #setClickable(boolean)
5948     *
5949     * @return true if the view is currently pressed, false otherwise
5950     */
5951    public boolean isPressed() {
5952        return (mPrivateFlags & PRESSED) == PRESSED;
5953    }
5954
5955    /**
5956     * Indicates whether this view will save its state (that is,
5957     * whether its {@link #onSaveInstanceState} method will be called).
5958     *
5959     * @return Returns true if the view state saving is enabled, else false.
5960     *
5961     * @see #setSaveEnabled(boolean)
5962     * @attr ref android.R.styleable#View_saveEnabled
5963     */
5964    public boolean isSaveEnabled() {
5965        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5966    }
5967
5968    /**
5969     * Controls whether the saving of this view's state is
5970     * enabled (that is, whether its {@link #onSaveInstanceState} method
5971     * will be called).  Note that even if freezing is enabled, the
5972     * view still must have an id assigned to it (via {@link #setId(int)})
5973     * for its state to be saved.  This flag can only disable the
5974     * saving of this view; any child views may still have their state saved.
5975     *
5976     * @param enabled Set to false to <em>disable</em> state saving, or true
5977     * (the default) to allow it.
5978     *
5979     * @see #isSaveEnabled()
5980     * @see #setId(int)
5981     * @see #onSaveInstanceState()
5982     * @attr ref android.R.styleable#View_saveEnabled
5983     */
5984    public void setSaveEnabled(boolean enabled) {
5985        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5986    }
5987
5988    /**
5989     * Gets whether the framework should discard touches when the view's
5990     * window is obscured by another visible window.
5991     * Refer to the {@link View} security documentation for more details.
5992     *
5993     * @return True if touch filtering is enabled.
5994     *
5995     * @see #setFilterTouchesWhenObscured(boolean)
5996     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5997     */
5998    @ViewDebug.ExportedProperty
5999    public boolean getFilterTouchesWhenObscured() {
6000        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6001    }
6002
6003    /**
6004     * Sets whether the framework should discard touches when the view's
6005     * window is obscured by another visible window.
6006     * Refer to the {@link View} security documentation for more details.
6007     *
6008     * @param enabled True if touch filtering should be enabled.
6009     *
6010     * @see #getFilterTouchesWhenObscured
6011     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6012     */
6013    public void setFilterTouchesWhenObscured(boolean enabled) {
6014        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6015                FILTER_TOUCHES_WHEN_OBSCURED);
6016    }
6017
6018    /**
6019     * Indicates whether the entire hierarchy under this view will save its
6020     * state when a state saving traversal occurs from its parent.  The default
6021     * is true; if false, these views will not be saved unless
6022     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6023     *
6024     * @return Returns true if the view state saving from parent is enabled, else false.
6025     *
6026     * @see #setSaveFromParentEnabled(boolean)
6027     */
6028    public boolean isSaveFromParentEnabled() {
6029        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6030    }
6031
6032    /**
6033     * Controls whether the entire hierarchy under this view will save its
6034     * state when a state saving traversal occurs from its parent.  The default
6035     * is true; if false, these views will not be saved unless
6036     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6037     *
6038     * @param enabled Set to false to <em>disable</em> state saving, or true
6039     * (the default) to allow it.
6040     *
6041     * @see #isSaveFromParentEnabled()
6042     * @see #setId(int)
6043     * @see #onSaveInstanceState()
6044     */
6045    public void setSaveFromParentEnabled(boolean enabled) {
6046        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6047    }
6048
6049
6050    /**
6051     * Returns whether this View is able to take focus.
6052     *
6053     * @return True if this view can take focus, or false otherwise.
6054     * @attr ref android.R.styleable#View_focusable
6055     */
6056    @ViewDebug.ExportedProperty(category = "focus")
6057    public final boolean isFocusable() {
6058        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6059    }
6060
6061    /**
6062     * When a view is focusable, it may not want to take focus when in touch mode.
6063     * For example, a button would like focus when the user is navigating via a D-pad
6064     * so that the user can click on it, but once the user starts touching the screen,
6065     * the button shouldn't take focus
6066     * @return Whether the view is focusable in touch mode.
6067     * @attr ref android.R.styleable#View_focusableInTouchMode
6068     */
6069    @ViewDebug.ExportedProperty
6070    public final boolean isFocusableInTouchMode() {
6071        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6072    }
6073
6074    /**
6075     * Find the nearest view in the specified direction that can take focus.
6076     * This does not actually give focus to that view.
6077     *
6078     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6079     *
6080     * @return The nearest focusable in the specified direction, or null if none
6081     *         can be found.
6082     */
6083    public View focusSearch(int direction) {
6084        if (mParent != null) {
6085            return mParent.focusSearch(this, direction);
6086        } else {
6087            return null;
6088        }
6089    }
6090
6091    /**
6092     * This method is the last chance for the focused view and its ancestors to
6093     * respond to an arrow key. This is called when the focused view did not
6094     * consume the key internally, nor could the view system find a new view in
6095     * the requested direction to give focus to.
6096     *
6097     * @param focused The currently focused view.
6098     * @param direction The direction focus wants to move. One of FOCUS_UP,
6099     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6100     * @return True if the this view consumed this unhandled move.
6101     */
6102    public boolean dispatchUnhandledMove(View focused, int direction) {
6103        return false;
6104    }
6105
6106    /**
6107     * If a user manually specified the next view id for a particular direction,
6108     * use the root to look up the view.
6109     * @param root The root view of the hierarchy containing this view.
6110     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6111     * or FOCUS_BACKWARD.
6112     * @return The user specified next view, or null if there is none.
6113     */
6114    View findUserSetNextFocus(View root, int direction) {
6115        switch (direction) {
6116            case FOCUS_LEFT:
6117                if (mNextFocusLeftId == View.NO_ID) return null;
6118                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6119            case FOCUS_RIGHT:
6120                if (mNextFocusRightId == View.NO_ID) return null;
6121                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6122            case FOCUS_UP:
6123                if (mNextFocusUpId == View.NO_ID) return null;
6124                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6125            case FOCUS_DOWN:
6126                if (mNextFocusDownId == View.NO_ID) return null;
6127                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6128            case FOCUS_FORWARD:
6129                if (mNextFocusForwardId == View.NO_ID) return null;
6130                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6131            case FOCUS_BACKWARD: {
6132                if (mID == View.NO_ID) return null;
6133                final int id = mID;
6134                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6135                    @Override
6136                    public boolean apply(View t) {
6137                        return t.mNextFocusForwardId == id;
6138                    }
6139                });
6140            }
6141        }
6142        return null;
6143    }
6144
6145    private View findViewInsideOutShouldExist(View root, final int childViewId) {
6146        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6147            @Override
6148            public boolean apply(View t) {
6149                return t.mID == childViewId;
6150            }
6151        });
6152
6153        if (result == null) {
6154            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
6155                    + "by user for id " + childViewId);
6156        }
6157        return result;
6158    }
6159
6160    /**
6161     * Find and return all focusable views that are descendants of this view,
6162     * possibly including this view if it is focusable itself.
6163     *
6164     * @param direction The direction of the focus
6165     * @return A list of focusable views
6166     */
6167    public ArrayList<View> getFocusables(int direction) {
6168        ArrayList<View> result = new ArrayList<View>(24);
6169        addFocusables(result, direction);
6170        return result;
6171    }
6172
6173    /**
6174     * Add any focusable views that are descendants of this view (possibly
6175     * including this view if it is focusable itself) to views.  If we are in touch mode,
6176     * only add views that are also focusable in touch mode.
6177     *
6178     * @param views Focusable views found so far
6179     * @param direction The direction of the focus
6180     */
6181    public void addFocusables(ArrayList<View> views, int direction) {
6182        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6183    }
6184
6185    /**
6186     * Adds any focusable views that are descendants of this view (possibly
6187     * including this view if it is focusable itself) to views. This method
6188     * adds all focusable views regardless if we are in touch mode or
6189     * only views focusable in touch mode if we are in touch mode or
6190     * only views that can take accessibility focus if accessibility is enabeld
6191     * depending on the focusable mode paramater.
6192     *
6193     * @param views Focusable views found so far or null if all we are interested is
6194     *        the number of focusables.
6195     * @param direction The direction of the focus.
6196     * @param focusableMode The type of focusables to be added.
6197     *
6198     * @see #FOCUSABLES_ALL
6199     * @see #FOCUSABLES_TOUCH_MODE
6200     */
6201    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6202        if (views == null) {
6203            return;
6204        }
6205        if ((focusableMode & FOCUSABLES_ACCESSIBILITY) == FOCUSABLES_ACCESSIBILITY) {
6206            if (isAccessibilityFocusable()) {
6207                views.add(this);
6208                return;
6209            }
6210        }
6211        if (!isFocusable()) {
6212            return;
6213        }
6214        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6215                && isInTouchMode() && !isFocusableInTouchMode()) {
6216            return;
6217        }
6218        views.add(this);
6219    }
6220
6221    /**
6222     * Finds the Views that contain given text. The containment is case insensitive.
6223     * The search is performed by either the text that the View renders or the content
6224     * description that describes the view for accessibility purposes and the view does
6225     * not render or both. Clients can specify how the search is to be performed via
6226     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6227     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6228     *
6229     * @param outViews The output list of matching Views.
6230     * @param searched The text to match against.
6231     *
6232     * @see #FIND_VIEWS_WITH_TEXT
6233     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6234     * @see #setContentDescription(CharSequence)
6235     */
6236    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6237        if (getAccessibilityNodeProvider() != null) {
6238            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6239                outViews.add(this);
6240            }
6241        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6242                && (searched != null && searched.length() > 0)
6243                && (mContentDescription != null && mContentDescription.length() > 0)) {
6244            String searchedLowerCase = searched.toString().toLowerCase();
6245            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6246            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6247                outViews.add(this);
6248            }
6249        }
6250    }
6251
6252    /**
6253     * Find and return all touchable views that are descendants of this view,
6254     * possibly including this view if it is touchable itself.
6255     *
6256     * @return A list of touchable views
6257     */
6258    public ArrayList<View> getTouchables() {
6259        ArrayList<View> result = new ArrayList<View>();
6260        addTouchables(result);
6261        return result;
6262    }
6263
6264    /**
6265     * Add any touchable views that are descendants of this view (possibly
6266     * including this view if it is touchable itself) to views.
6267     *
6268     * @param views Touchable views found so far
6269     */
6270    public void addTouchables(ArrayList<View> views) {
6271        final int viewFlags = mViewFlags;
6272
6273        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6274                && (viewFlags & ENABLED_MASK) == ENABLED) {
6275            views.add(this);
6276        }
6277    }
6278
6279    /**
6280     * Returns whether this View is accessibility focused.
6281     *
6282     * @return True if this View is accessibility focused.
6283     */
6284    boolean isAccessibilityFocused() {
6285        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6286    }
6287
6288    /**
6289     * Call this to try to give accessibility focus to this view.
6290     *
6291     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6292     * returns false or the view is no visible or the view already has accessibility
6293     * focus.
6294     *
6295     * See also {@link #focusSearch(int)}, which is what you call to say that you
6296     * have focus, and you want your parent to look for the next one.
6297     *
6298     * @return Whether this view actually took accessibility focus.
6299     *
6300     * @hide
6301     */
6302    public boolean requestAccessibilityFocus() {
6303        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6304        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6305            return false;
6306        }
6307        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6308            return false;
6309        }
6310        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6311            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6312            ViewRootImpl viewRootImpl = getViewRootImpl();
6313            if (viewRootImpl != null) {
6314                viewRootImpl.setAccessibilityFocusedHost(this);
6315            }
6316            invalidate();
6317            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6318            notifyAccessibilityStateChanged();
6319            return true;
6320        }
6321        return false;
6322    }
6323
6324    /**
6325     * Call this to try to clear accessibility focus of this view.
6326     *
6327     * See also {@link #focusSearch(int)}, which is what you call to say that you
6328     * have focus, and you want your parent to look for the next one.
6329     *
6330     * @hide
6331     */
6332    public void clearAccessibilityFocus() {
6333        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6334            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6335            invalidate();
6336            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6337            notifyAccessibilityStateChanged();
6338        }
6339        // Clear the global reference of accessibility focus if this
6340        // view or any of its descendants had accessibility focus.
6341        ViewRootImpl viewRootImpl = getViewRootImpl();
6342        if (viewRootImpl != null) {
6343            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6344            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6345                viewRootImpl.setAccessibilityFocusedHost(null);
6346            }
6347        }
6348    }
6349
6350    private void sendAccessibilityHoverEvent(int eventType) {
6351        // Since we are not delivering to a client accessibility events from not
6352        // important views (unless the clinet request that) we need to fire the
6353        // event from the deepest view exposed to the client. As a consequence if
6354        // the user crosses a not exposed view the client will see enter and exit
6355        // of the exposed predecessor followed by and enter and exit of that same
6356        // predecessor when entering and exiting the not exposed descendant. This
6357        // is fine since the client has a clear idea which view is hovered at the
6358        // price of a couple more events being sent. This is a simple and
6359        // working solution.
6360        View source = this;
6361        while (true) {
6362            if (source.includeForAccessibility()) {
6363                source.sendAccessibilityEvent(eventType);
6364                return;
6365            }
6366            ViewParent parent = source.getParent();
6367            if (parent instanceof View) {
6368                source = (View) parent;
6369            } else {
6370                return;
6371            }
6372        }
6373    }
6374
6375    private void requestAccessibilityFocusFromHover() {
6376        if (includeForAccessibility() && isActionableForAccessibility()) {
6377            requestAccessibilityFocus();
6378        } else {
6379            if (mParent != null) {
6380                View nextFocus = mParent.findViewToTakeAccessibilityFocusFromHover(this, this);
6381                if (nextFocus != null) {
6382                    nextFocus.requestAccessibilityFocus();
6383                }
6384            }
6385        }
6386    }
6387
6388    private boolean canTakeAccessibilityFocusFromHover() {
6389        if (includeForAccessibility() && isActionableForAccessibility()) {
6390            return true;
6391        }
6392        if (mParent != null) {
6393            return (mParent.findViewToTakeAccessibilityFocusFromHover(this, this) == this);
6394        }
6395        return false;
6396    }
6397
6398    /**
6399     * Clears accessibility focus without calling any callback methods
6400     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6401     * is used for clearing accessibility focus when giving this focus to
6402     * another view.
6403     */
6404    void clearAccessibilityFocusNoCallbacks() {
6405        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6406            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6407            invalidate();
6408        }
6409    }
6410
6411    /**
6412     * Call this to try to give focus to a specific view or to one of its
6413     * descendants.
6414     *
6415     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6416     * false), or if it is focusable and it is not focusable in touch mode
6417     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6418     *
6419     * See also {@link #focusSearch(int)}, which is what you call to say that you
6420     * have focus, and you want your parent to look for the next one.
6421     *
6422     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6423     * {@link #FOCUS_DOWN} and <code>null</code>.
6424     *
6425     * @return Whether this view or one of its descendants actually took focus.
6426     */
6427    public final boolean requestFocus() {
6428        return requestFocus(View.FOCUS_DOWN);
6429    }
6430
6431    /**
6432     * Call this to try to give focus to a specific view or to one of its
6433     * descendants and give it a hint about what direction focus is heading.
6434     *
6435     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6436     * false), or if it is focusable and it is not focusable in touch mode
6437     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6438     *
6439     * See also {@link #focusSearch(int)}, which is what you call to say that you
6440     * have focus, and you want your parent to look for the next one.
6441     *
6442     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6443     * <code>null</code> set for the previously focused rectangle.
6444     *
6445     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6446     * @return Whether this view or one of its descendants actually took focus.
6447     */
6448    public final boolean requestFocus(int direction) {
6449        return requestFocus(direction, null);
6450    }
6451
6452    /**
6453     * Call this to try to give focus to a specific view or to one of its descendants
6454     * and give it hints about the direction and a specific rectangle that the focus
6455     * is coming from.  The rectangle can help give larger views a finer grained hint
6456     * about where focus is coming from, and therefore, where to show selection, or
6457     * forward focus change internally.
6458     *
6459     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6460     * false), or if it is focusable and it is not focusable in touch mode
6461     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6462     *
6463     * A View will not take focus if it is not visible.
6464     *
6465     * A View will not take focus if one of its parents has
6466     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6467     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6468     *
6469     * See also {@link #focusSearch(int)}, which is what you call to say that you
6470     * have focus, and you want your parent to look for the next one.
6471     *
6472     * You may wish to override this method if your custom {@link View} has an internal
6473     * {@link View} that it wishes to forward the request to.
6474     *
6475     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6476     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6477     *        to give a finer grained hint about where focus is coming from.  May be null
6478     *        if there is no hint.
6479     * @return Whether this view or one of its descendants actually took focus.
6480     */
6481    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6482        return requestFocusNoSearch(direction, previouslyFocusedRect);
6483    }
6484
6485    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6486        // need to be focusable
6487        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6488                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6489            return false;
6490        }
6491
6492        // need to be focusable in touch mode if in touch mode
6493        if (isInTouchMode() &&
6494            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6495               return false;
6496        }
6497
6498        // need to not have any parents blocking us
6499        if (hasAncestorThatBlocksDescendantFocus()) {
6500            return false;
6501        }
6502
6503        handleFocusGainInternal(direction, previouslyFocusedRect);
6504        return true;
6505    }
6506
6507    /**
6508     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6509     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6510     * touch mode to request focus when they are touched.
6511     *
6512     * @return Whether this view or one of its descendants actually took focus.
6513     *
6514     * @see #isInTouchMode()
6515     *
6516     */
6517    public final boolean requestFocusFromTouch() {
6518        // Leave touch mode if we need to
6519        if (isInTouchMode()) {
6520            ViewRootImpl viewRoot = getViewRootImpl();
6521            if (viewRoot != null) {
6522                viewRoot.ensureTouchMode(false);
6523            }
6524        }
6525        return requestFocus(View.FOCUS_DOWN);
6526    }
6527
6528    /**
6529     * @return Whether any ancestor of this view blocks descendant focus.
6530     */
6531    private boolean hasAncestorThatBlocksDescendantFocus() {
6532        ViewParent ancestor = mParent;
6533        while (ancestor instanceof ViewGroup) {
6534            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6535            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6536                return true;
6537            } else {
6538                ancestor = vgAncestor.getParent();
6539            }
6540        }
6541        return false;
6542    }
6543
6544    /**
6545     * Gets the mode for determining whether this View is important for accessibility
6546     * which is if it fires accessibility events and if it is reported to
6547     * accessibility services that query the screen.
6548     *
6549     * @return The mode for determining whether a View is important for accessibility.
6550     *
6551     * @attr ref android.R.styleable#View_importantForAccessibility
6552     *
6553     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6554     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6555     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6556     */
6557    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6558            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6559            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6560            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6561        })
6562    public int getImportantForAccessibility() {
6563        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6564                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6565    }
6566
6567    /**
6568     * Sets how to determine whether this view is important for accessibility
6569     * which is if it fires accessibility events and if it is reported to
6570     * accessibility services that query the screen.
6571     *
6572     * @param mode How to determine whether this view is important for accessibility.
6573     *
6574     * @attr ref android.R.styleable#View_importantForAccessibility
6575     *
6576     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6577     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6578     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6579     */
6580    public void setImportantForAccessibility(int mode) {
6581        if (mode != getImportantForAccessibility()) {
6582            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6583            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6584                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6585            notifyAccessibilityStateChanged();
6586        }
6587    }
6588
6589    /**
6590     * Gets whether this view should be exposed for accessibility.
6591     *
6592     * @return Whether the view is exposed for accessibility.
6593     *
6594     * @hide
6595     */
6596    public boolean isImportantForAccessibility() {
6597        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6598                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6599        switch (mode) {
6600            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6601                return true;
6602            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6603                return false;
6604            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6605                return isActionableForAccessibility() || hasListenersForAccessibility();
6606            default:
6607                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6608                        + mode);
6609        }
6610    }
6611
6612    /**
6613     * Gets the mode for determining whether this View can take accessibility focus.
6614     *
6615     * @return The mode for determining whether a View can take accessibility focus.
6616     *
6617     * @attr ref android.R.styleable#View_accessibilityFocusable
6618     *
6619     * @see #ACCESSIBILITY_FOCUSABLE_YES
6620     * @see #ACCESSIBILITY_FOCUSABLE_NO
6621     * @see #ACCESSIBILITY_FOCUSABLE_AUTO
6622     *
6623     * @hide
6624     */
6625    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6626            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_AUTO, to = "auto"),
6627            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_YES, to = "yes"),
6628            @ViewDebug.IntToString(from = ACCESSIBILITY_FOCUSABLE_NO, to = "no")
6629        })
6630    public int getAccessibilityFocusable() {
6631        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSABLE_MASK) >>> ACCESSIBILITY_FOCUSABLE_SHIFT;
6632    }
6633
6634    /**
6635     * Sets how to determine whether this view can take accessibility focus.
6636     *
6637     * @param mode How to determine whether this view can take accessibility focus.
6638     *
6639     * @attr ref android.R.styleable#View_accessibilityFocusable
6640     *
6641     * @see #ACCESSIBILITY_FOCUSABLE_YES
6642     * @see #ACCESSIBILITY_FOCUSABLE_NO
6643     * @see #ACCESSIBILITY_FOCUSABLE_AUTO
6644     *
6645     * @hide
6646     */
6647    public void setAccessibilityFocusable(int mode) {
6648        if (mode != getAccessibilityFocusable()) {
6649            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSABLE_MASK;
6650            mPrivateFlags2 |= (mode << ACCESSIBILITY_FOCUSABLE_SHIFT)
6651                    & ACCESSIBILITY_FOCUSABLE_MASK;
6652            notifyAccessibilityStateChanged();
6653        }
6654    }
6655
6656    /**
6657     * Gets whether this view can take accessibility focus.
6658     *
6659     * @return Whether the view can take accessibility focus.
6660     *
6661     * @hide
6662     */
6663    public boolean isAccessibilityFocusable() {
6664        final int mode = (mPrivateFlags2 & ACCESSIBILITY_FOCUSABLE_MASK)
6665                >>> ACCESSIBILITY_FOCUSABLE_SHIFT;
6666        switch (mode) {
6667            case ACCESSIBILITY_FOCUSABLE_YES:
6668                return true;
6669            case ACCESSIBILITY_FOCUSABLE_NO:
6670                return false;
6671            case ACCESSIBILITY_FOCUSABLE_AUTO:
6672                return canTakeAccessibilityFocusFromHover()
6673                        || getAccessibilityNodeProvider() != null;
6674            default:
6675                throw new IllegalArgumentException("Unknow accessibility focusable mode: " + mode);
6676        }
6677    }
6678
6679    /**
6680     * Gets the parent for accessibility purposes. Note that the parent for
6681     * accessibility is not necessary the immediate parent. It is the first
6682     * predecessor that is important for accessibility.
6683     *
6684     * @return The parent for accessibility purposes.
6685     */
6686    public ViewParent getParentForAccessibility() {
6687        if (mParent instanceof View) {
6688            View parentView = (View) mParent;
6689            if (parentView.includeForAccessibility()) {
6690                return mParent;
6691            } else {
6692                return mParent.getParentForAccessibility();
6693            }
6694        }
6695        return null;
6696    }
6697
6698    /**
6699     * Adds the children of a given View for accessibility. Since some Views are
6700     * not important for accessibility the children for accessibility are not
6701     * necessarily direct children of the riew, rather they are the first level of
6702     * descendants important for accessibility.
6703     *
6704     * @param children The list of children for accessibility.
6705     */
6706    public void addChildrenForAccessibility(ArrayList<View> children) {
6707        if (includeForAccessibility()) {
6708            children.add(this);
6709        }
6710    }
6711
6712    /**
6713     * Whether to regard this view for accessibility. A view is regarded for
6714     * accessibility if it is important for accessibility or the querying
6715     * accessibility service has explicitly requested that view not
6716     * important for accessibility are regarded.
6717     *
6718     * @return Whether to regard the view for accessibility.
6719     *
6720     * @hide
6721     */
6722    public boolean includeForAccessibility() {
6723        if (mAttachInfo != null) {
6724            if (!mAttachInfo.mIncludeNotImportantViews) {
6725                return isImportantForAccessibility();
6726            }
6727            return true;
6728        }
6729        return false;
6730    }
6731
6732    /**
6733     * Returns whether the View is considered actionable from
6734     * accessibility perspective. Such view are important for
6735     * accessiiblity.
6736     *
6737     * @return True if the view is actionable for accessibility.
6738     *
6739     * @hide
6740     */
6741    public boolean isActionableForAccessibility() {
6742        return (isClickable() || isLongClickable() || isFocusable());
6743    }
6744
6745    /**
6746     * Returns whether the View has registered callbacks wich makes it
6747     * important for accessiiblity.
6748     *
6749     * @return True if the view is actionable for accessibility.
6750     */
6751    private boolean hasListenersForAccessibility() {
6752        ListenerInfo info = getListenerInfo();
6753        return mTouchDelegate != null || info.mOnKeyListener != null
6754                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6755                || info.mOnHoverListener != null || info.mOnDragListener != null;
6756    }
6757
6758    /**
6759     * Notifies accessibility services that some view's important for
6760     * accessibility state has changed. Note that such notifications
6761     * are made at most once every
6762     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6763     * to avoid unnecessary load to the system. Also once a view has
6764     * made a notifucation this method is a NOP until the notification has
6765     * been sent to clients.
6766     *
6767     * @hide
6768     *
6769     * TODO: Makse sure this method is called for any view state change
6770     *       that is interesting for accessilility purposes.
6771     */
6772    public void notifyAccessibilityStateChanged() {
6773        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6774            return;
6775        }
6776        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6777            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6778            if (mParent != null) {
6779                mParent.childAccessibilityStateChanged(this);
6780            }
6781        }
6782    }
6783
6784    /**
6785     * Reset the state indicating the this view has requested clients
6786     * interested in its accessiblity state to be notified.
6787     *
6788     * @hide
6789     */
6790    public void resetAccessibilityStateChanged() {
6791        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6792    }
6793
6794    /**
6795     * Performs the specified accessibility action on the view. For
6796     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6797    * <p>
6798    * If an {@link AccessibilityDelegate} has been specified via calling
6799    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6800    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6801    * is responsible for handling this call.
6802    * </p>
6803     *
6804     * @param action The action to perform.
6805     * @param arguments Optional action arguments.
6806     * @return Whether the action was performed.
6807     */
6808    public boolean performAccessibilityAction(int action, Bundle arguments) {
6809      if (mAccessibilityDelegate != null) {
6810          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6811      } else {
6812          return performAccessibilityActionInternal(action, arguments);
6813      }
6814    }
6815
6816   /**
6817    * @see #performAccessibilityAction(int, Bundle)
6818    *
6819    * Note: Called from the default {@link AccessibilityDelegate}.
6820    */
6821    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6822        switch (action) {
6823            case AccessibilityNodeInfo.ACTION_CLICK: {
6824                if (isClickable()) {
6825                    return performClick();
6826                }
6827            } break;
6828            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6829                if (isLongClickable()) {
6830                    return performLongClick();
6831                }
6832            } break;
6833            case AccessibilityNodeInfo.ACTION_FOCUS: {
6834                if (!hasFocus()) {
6835                    // Get out of touch mode since accessibility
6836                    // wants to move focus around.
6837                    getViewRootImpl().ensureTouchMode(false);
6838                    return requestFocus();
6839                }
6840            } break;
6841            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6842                if (hasFocus()) {
6843                    clearFocus();
6844                    return !isFocused();
6845                }
6846            } break;
6847            case AccessibilityNodeInfo.ACTION_SELECT: {
6848                if (!isSelected()) {
6849                    setSelected(true);
6850                    return isSelected();
6851                }
6852            } break;
6853            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6854                if (isSelected()) {
6855                    setSelected(false);
6856                    return !isSelected();
6857                }
6858            } break;
6859            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6860                final int mode = getAccessibilityFocusable();
6861                if (!isAccessibilityFocused()
6862                        && (mode == ACCESSIBILITY_FOCUSABLE_YES
6863                                || mode == ACCESSIBILITY_FOCUSABLE_AUTO)) {
6864                    return requestAccessibilityFocus();
6865                }
6866            } break;
6867            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6868                if (isAccessibilityFocused()) {
6869                    clearAccessibilityFocus();
6870                    return true;
6871                }
6872            } break;
6873            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6874                if (arguments != null) {
6875                    final int granularity = arguments.getInt(
6876                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6877                    return nextAtGranularity(granularity);
6878                }
6879            } break;
6880            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6881                if (arguments != null) {
6882                    final int granularity = arguments.getInt(
6883                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6884                    return previousAtGranularity(granularity);
6885                }
6886            } break;
6887        }
6888        return false;
6889    }
6890
6891    private boolean nextAtGranularity(int granularity) {
6892        CharSequence text = getIterableTextForAccessibility();
6893        if (text == null || text.length() == 0) {
6894            return false;
6895        }
6896        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6897        if (iterator == null) {
6898            return false;
6899        }
6900        final int current = getAccessibilityCursorPosition();
6901        final int[] range = iterator.following(current);
6902        if (range == null) {
6903            return false;
6904        }
6905        final int start = range[0];
6906        final int end = range[1];
6907        setAccessibilityCursorPosition(end);
6908        sendViewTextTraversedAtGranularityEvent(
6909                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6910                granularity, start, end);
6911        return true;
6912    }
6913
6914    private boolean previousAtGranularity(int granularity) {
6915        CharSequence text = getIterableTextForAccessibility();
6916        if (text == null || text.length() == 0) {
6917            return false;
6918        }
6919        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6920        if (iterator == null) {
6921            return false;
6922        }
6923        int current = getAccessibilityCursorPosition();
6924        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6925            current = text.length();
6926        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6927            // When traversing by character we always put the cursor after the character
6928            // to ease edit and have to compensate before asking the for previous segment.
6929            current--;
6930        }
6931        final int[] range = iterator.preceding(current);
6932        if (range == null) {
6933            return false;
6934        }
6935        final int start = range[0];
6936        final int end = range[1];
6937        // Always put the cursor after the character to ease edit.
6938        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6939            setAccessibilityCursorPosition(end);
6940        } else {
6941            setAccessibilityCursorPosition(start);
6942        }
6943        sendViewTextTraversedAtGranularityEvent(
6944                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6945                granularity, start, end);
6946        return true;
6947    }
6948
6949    /**
6950     * Gets the text reported for accessibility purposes.
6951     *
6952     * @return The accessibility text.
6953     *
6954     * @hide
6955     */
6956    public CharSequence getIterableTextForAccessibility() {
6957        return mContentDescription;
6958    }
6959
6960    /**
6961     * @hide
6962     */
6963    public int getAccessibilityCursorPosition() {
6964        return mAccessibilityCursorPosition;
6965    }
6966
6967    /**
6968     * @hide
6969     */
6970    public void setAccessibilityCursorPosition(int position) {
6971        mAccessibilityCursorPosition = position;
6972    }
6973
6974    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6975            int fromIndex, int toIndex) {
6976        if (mParent == null) {
6977            return;
6978        }
6979        AccessibilityEvent event = AccessibilityEvent.obtain(
6980                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6981        onInitializeAccessibilityEvent(event);
6982        onPopulateAccessibilityEvent(event);
6983        event.setFromIndex(fromIndex);
6984        event.setToIndex(toIndex);
6985        event.setAction(action);
6986        event.setMovementGranularity(granularity);
6987        mParent.requestSendAccessibilityEvent(this, event);
6988    }
6989
6990    /**
6991     * @hide
6992     */
6993    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6994        switch (granularity) {
6995            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6996                CharSequence text = getIterableTextForAccessibility();
6997                if (text != null && text.length() > 0) {
6998                    CharacterTextSegmentIterator iterator =
6999                        CharacterTextSegmentIterator.getInstance(
7000                                mContext.getResources().getConfiguration().locale);
7001                    iterator.initialize(text.toString());
7002                    return iterator;
7003                }
7004            } break;
7005            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7006                CharSequence text = getIterableTextForAccessibility();
7007                if (text != null && text.length() > 0) {
7008                    WordTextSegmentIterator iterator =
7009                        WordTextSegmentIterator.getInstance(
7010                                mContext.getResources().getConfiguration().locale);
7011                    iterator.initialize(text.toString());
7012                    return iterator;
7013                }
7014            } break;
7015            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7016                CharSequence text = getIterableTextForAccessibility();
7017                if (text != null && text.length() > 0) {
7018                    ParagraphTextSegmentIterator iterator =
7019                        ParagraphTextSegmentIterator.getInstance();
7020                    iterator.initialize(text.toString());
7021                    return iterator;
7022                }
7023            } break;
7024        }
7025        return null;
7026    }
7027
7028    /**
7029     * @hide
7030     */
7031    public void dispatchStartTemporaryDetach() {
7032        clearAccessibilityFocus();
7033        clearDisplayList();
7034
7035        onStartTemporaryDetach();
7036    }
7037
7038    /**
7039     * This is called when a container is going to temporarily detach a child, with
7040     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7041     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7042     * {@link #onDetachedFromWindow()} when the container is done.
7043     */
7044    public void onStartTemporaryDetach() {
7045        removeUnsetPressCallback();
7046        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
7047    }
7048
7049    /**
7050     * @hide
7051     */
7052    public void dispatchFinishTemporaryDetach() {
7053        onFinishTemporaryDetach();
7054    }
7055
7056    /**
7057     * Called after {@link #onStartTemporaryDetach} when the container is done
7058     * changing the view.
7059     */
7060    public void onFinishTemporaryDetach() {
7061    }
7062
7063    /**
7064     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7065     * for this view's window.  Returns null if the view is not currently attached
7066     * to the window.  Normally you will not need to use this directly, but
7067     * just use the standard high-level event callbacks like
7068     * {@link #onKeyDown(int, KeyEvent)}.
7069     */
7070    public KeyEvent.DispatcherState getKeyDispatcherState() {
7071        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7072    }
7073
7074    /**
7075     * Dispatch a key event before it is processed by any input method
7076     * associated with the view hierarchy.  This can be used to intercept
7077     * key events in special situations before the IME consumes them; a
7078     * typical example would be handling the BACK key to update the application's
7079     * UI instead of allowing the IME to see it and close itself.
7080     *
7081     * @param event The key event to be dispatched.
7082     * @return True if the event was handled, false otherwise.
7083     */
7084    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7085        return onKeyPreIme(event.getKeyCode(), event);
7086    }
7087
7088    /**
7089     * Dispatch a key event to the next view on the focus path. This path runs
7090     * from the top of the view tree down to the currently focused view. If this
7091     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7092     * the next node down the focus path. This method also fires any key
7093     * listeners.
7094     *
7095     * @param event The key event to be dispatched.
7096     * @return True if the event was handled, false otherwise.
7097     */
7098    public boolean dispatchKeyEvent(KeyEvent event) {
7099        if (mInputEventConsistencyVerifier != null) {
7100            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7101        }
7102
7103        // Give any attached key listener a first crack at the event.
7104        //noinspection SimplifiableIfStatement
7105        ListenerInfo li = mListenerInfo;
7106        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7107                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7108            return true;
7109        }
7110
7111        if (event.dispatch(this, mAttachInfo != null
7112                ? mAttachInfo.mKeyDispatchState : null, this)) {
7113            return true;
7114        }
7115
7116        if (mInputEventConsistencyVerifier != null) {
7117            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7118        }
7119        return false;
7120    }
7121
7122    /**
7123     * Dispatches a key shortcut event.
7124     *
7125     * @param event The key event to be dispatched.
7126     * @return True if the event was handled by the view, false otherwise.
7127     */
7128    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7129        return onKeyShortcut(event.getKeyCode(), event);
7130    }
7131
7132    /**
7133     * Pass the touch screen motion event down to the target view, or this
7134     * view if it is the target.
7135     *
7136     * @param event The motion event to be dispatched.
7137     * @return True if the event was handled by the view, false otherwise.
7138     */
7139    public boolean dispatchTouchEvent(MotionEvent event) {
7140        if (mInputEventConsistencyVerifier != null) {
7141            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7142        }
7143
7144        if (onFilterTouchEventForSecurity(event)) {
7145            //noinspection SimplifiableIfStatement
7146            ListenerInfo li = mListenerInfo;
7147            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7148                    && li.mOnTouchListener.onTouch(this, event)) {
7149                return true;
7150            }
7151
7152            if (onTouchEvent(event)) {
7153                return true;
7154            }
7155        }
7156
7157        if (mInputEventConsistencyVerifier != null) {
7158            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7159        }
7160        return false;
7161    }
7162
7163    /**
7164     * Filter the touch event to apply security policies.
7165     *
7166     * @param event The motion event to be filtered.
7167     * @return True if the event should be dispatched, false if the event should be dropped.
7168     *
7169     * @see #getFilterTouchesWhenObscured
7170     */
7171    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7172        //noinspection RedundantIfStatement
7173        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7174                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7175            // Window is obscured, drop this touch.
7176            return false;
7177        }
7178        return true;
7179    }
7180
7181    /**
7182     * Pass a trackball motion event down to the focused view.
7183     *
7184     * @param event The motion event to be dispatched.
7185     * @return True if the event was handled by the view, false otherwise.
7186     */
7187    public boolean dispatchTrackballEvent(MotionEvent event) {
7188        if (mInputEventConsistencyVerifier != null) {
7189            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7190        }
7191
7192        return onTrackballEvent(event);
7193    }
7194
7195    /**
7196     * Dispatch a generic motion event.
7197     * <p>
7198     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7199     * are delivered to the view under the pointer.  All other generic motion events are
7200     * delivered to the focused view.  Hover events are handled specially and are delivered
7201     * to {@link #onHoverEvent(MotionEvent)}.
7202     * </p>
7203     *
7204     * @param event The motion event to be dispatched.
7205     * @return True if the event was handled by the view, false otherwise.
7206     */
7207    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7208        if (mInputEventConsistencyVerifier != null) {
7209            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7210        }
7211
7212        final int source = event.getSource();
7213        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7214            final int action = event.getAction();
7215            if (action == MotionEvent.ACTION_HOVER_ENTER
7216                    || action == MotionEvent.ACTION_HOVER_MOVE
7217                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7218                if (dispatchHoverEvent(event)) {
7219                    return true;
7220                }
7221            } else if (dispatchGenericPointerEvent(event)) {
7222                return true;
7223            }
7224        } else if (dispatchGenericFocusedEvent(event)) {
7225            return true;
7226        }
7227
7228        if (dispatchGenericMotionEventInternal(event)) {
7229            return true;
7230        }
7231
7232        if (mInputEventConsistencyVerifier != null) {
7233            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7234        }
7235        return false;
7236    }
7237
7238    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7239        //noinspection SimplifiableIfStatement
7240        ListenerInfo li = mListenerInfo;
7241        if (li != null && li.mOnGenericMotionListener != null
7242                && (mViewFlags & ENABLED_MASK) == ENABLED
7243                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7244            return true;
7245        }
7246
7247        if (onGenericMotionEvent(event)) {
7248            return true;
7249        }
7250
7251        if (mInputEventConsistencyVerifier != null) {
7252            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7253        }
7254        return false;
7255    }
7256
7257    /**
7258     * Dispatch a hover event.
7259     * <p>
7260     * Do not call this method directly.
7261     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7262     * </p>
7263     *
7264     * @param event The motion event to be dispatched.
7265     * @return True if the event was handled by the view, false otherwise.
7266     */
7267    protected boolean dispatchHoverEvent(MotionEvent event) {
7268        //noinspection SimplifiableIfStatement
7269        ListenerInfo li = mListenerInfo;
7270        if (li != null && li.mOnHoverListener != null
7271                && (mViewFlags & ENABLED_MASK) == ENABLED
7272                && li.mOnHoverListener.onHover(this, event)) {
7273            return true;
7274        }
7275
7276        return onHoverEvent(event);
7277    }
7278
7279    /**
7280     * Returns true if the view has a child to which it has recently sent
7281     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7282     * it does not have a hovered child, then it must be the innermost hovered view.
7283     * @hide
7284     */
7285    protected boolean hasHoveredChild() {
7286        return false;
7287    }
7288
7289    /**
7290     * Dispatch a generic motion event to the view under the first pointer.
7291     * <p>
7292     * Do not call this method directly.
7293     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7294     * </p>
7295     *
7296     * @param event The motion event to be dispatched.
7297     * @return True if the event was handled by the view, false otherwise.
7298     */
7299    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7300        return false;
7301    }
7302
7303    /**
7304     * Dispatch a generic motion event to the currently focused view.
7305     * <p>
7306     * Do not call this method directly.
7307     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7308     * </p>
7309     *
7310     * @param event The motion event to be dispatched.
7311     * @return True if the event was handled by the view, false otherwise.
7312     */
7313    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7314        return false;
7315    }
7316
7317    /**
7318     * Dispatch a pointer event.
7319     * <p>
7320     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7321     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7322     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7323     * and should not be expected to handle other pointing device features.
7324     * </p>
7325     *
7326     * @param event The motion event to be dispatched.
7327     * @return True if the event was handled by the view, false otherwise.
7328     * @hide
7329     */
7330    public final boolean dispatchPointerEvent(MotionEvent event) {
7331        if (event.isTouchEvent()) {
7332            return dispatchTouchEvent(event);
7333        } else {
7334            return dispatchGenericMotionEvent(event);
7335        }
7336    }
7337
7338    /**
7339     * Called when the window containing this view gains or loses window focus.
7340     * ViewGroups should override to route to their children.
7341     *
7342     * @param hasFocus True if the window containing this view now has focus,
7343     *        false otherwise.
7344     */
7345    public void dispatchWindowFocusChanged(boolean hasFocus) {
7346        onWindowFocusChanged(hasFocus);
7347    }
7348
7349    /**
7350     * Called when the window containing this view gains or loses focus.  Note
7351     * that this is separate from view focus: to receive key events, both
7352     * your view and its window must have focus.  If a window is displayed
7353     * on top of yours that takes input focus, then your own window will lose
7354     * focus but the view focus will remain unchanged.
7355     *
7356     * @param hasWindowFocus True if the window containing this view now has
7357     *        focus, false otherwise.
7358     */
7359    public void onWindowFocusChanged(boolean hasWindowFocus) {
7360        InputMethodManager imm = InputMethodManager.peekInstance();
7361        if (!hasWindowFocus) {
7362            if (isPressed()) {
7363                setPressed(false);
7364            }
7365            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7366                imm.focusOut(this);
7367            }
7368            removeLongPressCallback();
7369            removeTapCallback();
7370            onFocusLost();
7371        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7372            imm.focusIn(this);
7373        }
7374        refreshDrawableState();
7375    }
7376
7377    /**
7378     * Returns true if this view is in a window that currently has window focus.
7379     * Note that this is not the same as the view itself having focus.
7380     *
7381     * @return True if this view is in a window that currently has window focus.
7382     */
7383    public boolean hasWindowFocus() {
7384        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7385    }
7386
7387    /**
7388     * Dispatch a view visibility change down the view hierarchy.
7389     * ViewGroups should override to route to their children.
7390     * @param changedView The view whose visibility changed. Could be 'this' or
7391     * an ancestor view.
7392     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7393     * {@link #INVISIBLE} or {@link #GONE}.
7394     */
7395    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7396        onVisibilityChanged(changedView, visibility);
7397    }
7398
7399    /**
7400     * Called when the visibility of the view or an ancestor of the view is changed.
7401     * @param changedView The view whose visibility changed. Could be 'this' or
7402     * an ancestor view.
7403     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7404     * {@link #INVISIBLE} or {@link #GONE}.
7405     */
7406    protected void onVisibilityChanged(View changedView, int visibility) {
7407        if (visibility == VISIBLE) {
7408            if (mAttachInfo != null) {
7409                initialAwakenScrollBars();
7410            } else {
7411                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7412            }
7413        }
7414    }
7415
7416    /**
7417     * Dispatch a hint about whether this view is displayed. For instance, when
7418     * a View moves out of the screen, it might receives a display hint indicating
7419     * the view is not displayed. Applications should not <em>rely</em> on this hint
7420     * as there is no guarantee that they will receive one.
7421     *
7422     * @param hint A hint about whether or not this view is displayed:
7423     * {@link #VISIBLE} or {@link #INVISIBLE}.
7424     */
7425    public void dispatchDisplayHint(int hint) {
7426        onDisplayHint(hint);
7427    }
7428
7429    /**
7430     * Gives this view a hint about whether is displayed or not. For instance, when
7431     * a View moves out of the screen, it might receives a display hint indicating
7432     * the view is not displayed. Applications should not <em>rely</em> on this hint
7433     * as there is no guarantee that they will receive one.
7434     *
7435     * @param hint A hint about whether or not this view is displayed:
7436     * {@link #VISIBLE} or {@link #INVISIBLE}.
7437     */
7438    protected void onDisplayHint(int hint) {
7439    }
7440
7441    /**
7442     * Dispatch a window visibility change down the view hierarchy.
7443     * ViewGroups should override to route to their children.
7444     *
7445     * @param visibility The new visibility of the window.
7446     *
7447     * @see #onWindowVisibilityChanged(int)
7448     */
7449    public void dispatchWindowVisibilityChanged(int visibility) {
7450        onWindowVisibilityChanged(visibility);
7451    }
7452
7453    /**
7454     * Called when the window containing has change its visibility
7455     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7456     * that this tells you whether or not your window is being made visible
7457     * to the window manager; this does <em>not</em> tell you whether or not
7458     * your window is obscured by other windows on the screen, even if it
7459     * is itself visible.
7460     *
7461     * @param visibility The new visibility of the window.
7462     */
7463    protected void onWindowVisibilityChanged(int visibility) {
7464        if (visibility == VISIBLE) {
7465            initialAwakenScrollBars();
7466        }
7467    }
7468
7469    /**
7470     * Returns the current visibility of the window this view is attached to
7471     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7472     *
7473     * @return Returns the current visibility of the view's window.
7474     */
7475    public int getWindowVisibility() {
7476        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7477    }
7478
7479    /**
7480     * Retrieve the overall visible display size in which the window this view is
7481     * attached to has been positioned in.  This takes into account screen
7482     * decorations above the window, for both cases where the window itself
7483     * is being position inside of them or the window is being placed under
7484     * then and covered insets are used for the window to position its content
7485     * inside.  In effect, this tells you the available area where content can
7486     * be placed and remain visible to users.
7487     *
7488     * <p>This function requires an IPC back to the window manager to retrieve
7489     * the requested information, so should not be used in performance critical
7490     * code like drawing.
7491     *
7492     * @param outRect Filled in with the visible display frame.  If the view
7493     * is not attached to a window, this is simply the raw display size.
7494     */
7495    public void getWindowVisibleDisplayFrame(Rect outRect) {
7496        if (mAttachInfo != null) {
7497            try {
7498                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7499            } catch (RemoteException e) {
7500                return;
7501            }
7502            // XXX This is really broken, and probably all needs to be done
7503            // in the window manager, and we need to know more about whether
7504            // we want the area behind or in front of the IME.
7505            final Rect insets = mAttachInfo.mVisibleInsets;
7506            outRect.left += insets.left;
7507            outRect.top += insets.top;
7508            outRect.right -= insets.right;
7509            outRect.bottom -= insets.bottom;
7510            return;
7511        }
7512        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7513        d.getRectSize(outRect);
7514    }
7515
7516    /**
7517     * Dispatch a notification about a resource configuration change down
7518     * the view hierarchy.
7519     * ViewGroups should override to route to their children.
7520     *
7521     * @param newConfig The new resource configuration.
7522     *
7523     * @see #onConfigurationChanged(android.content.res.Configuration)
7524     */
7525    public void dispatchConfigurationChanged(Configuration newConfig) {
7526        onConfigurationChanged(newConfig);
7527    }
7528
7529    /**
7530     * Called when the current configuration of the resources being used
7531     * by the application have changed.  You can use this to decide when
7532     * to reload resources that can changed based on orientation and other
7533     * configuration characterstics.  You only need to use this if you are
7534     * not relying on the normal {@link android.app.Activity} mechanism of
7535     * recreating the activity instance upon a configuration change.
7536     *
7537     * @param newConfig The new resource configuration.
7538     */
7539    protected void onConfigurationChanged(Configuration newConfig) {
7540    }
7541
7542    /**
7543     * Private function to aggregate all per-view attributes in to the view
7544     * root.
7545     */
7546    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7547        performCollectViewAttributes(attachInfo, visibility);
7548    }
7549
7550    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7551        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7552            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7553                attachInfo.mKeepScreenOn = true;
7554            }
7555            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7556            ListenerInfo li = mListenerInfo;
7557            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7558                attachInfo.mHasSystemUiListeners = true;
7559            }
7560        }
7561    }
7562
7563    void needGlobalAttributesUpdate(boolean force) {
7564        final AttachInfo ai = mAttachInfo;
7565        if (ai != null) {
7566            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7567                    || ai.mHasSystemUiListeners) {
7568                ai.mRecomputeGlobalAttributes = true;
7569            }
7570        }
7571    }
7572
7573    /**
7574     * Returns whether the device is currently in touch mode.  Touch mode is entered
7575     * once the user begins interacting with the device by touch, and affects various
7576     * things like whether focus is always visible to the user.
7577     *
7578     * @return Whether the device is in touch mode.
7579     */
7580    @ViewDebug.ExportedProperty
7581    public boolean isInTouchMode() {
7582        if (mAttachInfo != null) {
7583            return mAttachInfo.mInTouchMode;
7584        } else {
7585            return ViewRootImpl.isInTouchMode();
7586        }
7587    }
7588
7589    /**
7590     * Returns the context the view is running in, through which it can
7591     * access the current theme, resources, etc.
7592     *
7593     * @return The view's Context.
7594     */
7595    @ViewDebug.CapturedViewProperty
7596    public final Context getContext() {
7597        return mContext;
7598    }
7599
7600    /**
7601     * Handle a key event before it is processed by any input method
7602     * associated with the view hierarchy.  This can be used to intercept
7603     * key events in special situations before the IME consumes them; a
7604     * typical example would be handling the BACK key to update the application's
7605     * UI instead of allowing the IME to see it and close itself.
7606     *
7607     * @param keyCode The value in event.getKeyCode().
7608     * @param event Description of the key event.
7609     * @return If you handled the event, return true. If you want to allow the
7610     *         event to be handled by the next receiver, return false.
7611     */
7612    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7613        return false;
7614    }
7615
7616    /**
7617     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7618     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7619     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7620     * is released, if the view is enabled and clickable.
7621     *
7622     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7623     * although some may elect to do so in some situations. Do not rely on this to
7624     * catch software key presses.
7625     *
7626     * @param keyCode A key code that represents the button pressed, from
7627     *                {@link android.view.KeyEvent}.
7628     * @param event   The KeyEvent object that defines the button action.
7629     */
7630    public boolean onKeyDown(int keyCode, KeyEvent event) {
7631        boolean result = false;
7632
7633        switch (keyCode) {
7634            case KeyEvent.KEYCODE_DPAD_CENTER:
7635            case KeyEvent.KEYCODE_ENTER: {
7636                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7637                    return true;
7638                }
7639                // Long clickable items don't necessarily have to be clickable
7640                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7641                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7642                        (event.getRepeatCount() == 0)) {
7643                    setPressed(true);
7644                    checkForLongClick(0);
7645                    return true;
7646                }
7647                break;
7648            }
7649        }
7650        return result;
7651    }
7652
7653    /**
7654     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7655     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7656     * the event).
7657     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7658     * although some may elect to do so in some situations. Do not rely on this to
7659     * catch software key presses.
7660     */
7661    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7662        return false;
7663    }
7664
7665    /**
7666     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7667     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7668     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7669     * {@link KeyEvent#KEYCODE_ENTER} is released.
7670     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7671     * although some may elect to do so in some situations. Do not rely on this to
7672     * catch software key presses.
7673     *
7674     * @param keyCode A key code that represents the button pressed, from
7675     *                {@link android.view.KeyEvent}.
7676     * @param event   The KeyEvent object that defines the button action.
7677     */
7678    public boolean onKeyUp(int keyCode, KeyEvent event) {
7679        boolean result = false;
7680
7681        switch (keyCode) {
7682            case KeyEvent.KEYCODE_DPAD_CENTER:
7683            case KeyEvent.KEYCODE_ENTER: {
7684                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7685                    return true;
7686                }
7687                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7688                    setPressed(false);
7689
7690                    if (!mHasPerformedLongPress) {
7691                        // This is a tap, so remove the longpress check
7692                        removeLongPressCallback();
7693
7694                        result = performClick();
7695                    }
7696                }
7697                break;
7698            }
7699        }
7700        return result;
7701    }
7702
7703    /**
7704     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7705     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7706     * the event).
7707     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7708     * although some may elect to do so in some situations. Do not rely on this to
7709     * catch software key presses.
7710     *
7711     * @param keyCode     A key code that represents the button pressed, from
7712     *                    {@link android.view.KeyEvent}.
7713     * @param repeatCount The number of times the action was made.
7714     * @param event       The KeyEvent object that defines the button action.
7715     */
7716    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7717        return false;
7718    }
7719
7720    /**
7721     * Called on the focused view when a key shortcut event is not handled.
7722     * Override this method to implement local key shortcuts for the View.
7723     * Key shortcuts can also be implemented by setting the
7724     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7725     *
7726     * @param keyCode The value in event.getKeyCode().
7727     * @param event Description of the key event.
7728     * @return If you handled the event, return true. If you want to allow the
7729     *         event to be handled by the next receiver, return false.
7730     */
7731    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7732        return false;
7733    }
7734
7735    /**
7736     * Check whether the called view is a text editor, in which case it
7737     * would make sense to automatically display a soft input window for
7738     * it.  Subclasses should override this if they implement
7739     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7740     * a call on that method would return a non-null InputConnection, and
7741     * they are really a first-class editor that the user would normally
7742     * start typing on when the go into a window containing your view.
7743     *
7744     * <p>The default implementation always returns false.  This does
7745     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7746     * will not be called or the user can not otherwise perform edits on your
7747     * view; it is just a hint to the system that this is not the primary
7748     * purpose of this view.
7749     *
7750     * @return Returns true if this view is a text editor, else false.
7751     */
7752    public boolean onCheckIsTextEditor() {
7753        return false;
7754    }
7755
7756    /**
7757     * Create a new InputConnection for an InputMethod to interact
7758     * with the view.  The default implementation returns null, since it doesn't
7759     * support input methods.  You can override this to implement such support.
7760     * This is only needed for views that take focus and text input.
7761     *
7762     * <p>When implementing this, you probably also want to implement
7763     * {@link #onCheckIsTextEditor()} to indicate you will return a
7764     * non-null InputConnection.
7765     *
7766     * @param outAttrs Fill in with attribute information about the connection.
7767     */
7768    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7769        return null;
7770    }
7771
7772    /**
7773     * Called by the {@link android.view.inputmethod.InputMethodManager}
7774     * when a view who is not the current
7775     * input connection target is trying to make a call on the manager.  The
7776     * default implementation returns false; you can override this to return
7777     * true for certain views if you are performing InputConnection proxying
7778     * to them.
7779     * @param view The View that is making the InputMethodManager call.
7780     * @return Return true to allow the call, false to reject.
7781     */
7782    public boolean checkInputConnectionProxy(View view) {
7783        return false;
7784    }
7785
7786    /**
7787     * Show the context menu for this view. It is not safe to hold on to the
7788     * menu after returning from this method.
7789     *
7790     * You should normally not overload this method. Overload
7791     * {@link #onCreateContextMenu(ContextMenu)} or define an
7792     * {@link OnCreateContextMenuListener} to add items to the context menu.
7793     *
7794     * @param menu The context menu to populate
7795     */
7796    public void createContextMenu(ContextMenu menu) {
7797        ContextMenuInfo menuInfo = getContextMenuInfo();
7798
7799        // Sets the current menu info so all items added to menu will have
7800        // my extra info set.
7801        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7802
7803        onCreateContextMenu(menu);
7804        ListenerInfo li = mListenerInfo;
7805        if (li != null && li.mOnCreateContextMenuListener != null) {
7806            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7807        }
7808
7809        // Clear the extra information so subsequent items that aren't mine don't
7810        // have my extra info.
7811        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7812
7813        if (mParent != null) {
7814            mParent.createContextMenu(menu);
7815        }
7816    }
7817
7818    /**
7819     * Views should implement this if they have extra information to associate
7820     * with the context menu. The return result is supplied as a parameter to
7821     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7822     * callback.
7823     *
7824     * @return Extra information about the item for which the context menu
7825     *         should be shown. This information will vary across different
7826     *         subclasses of View.
7827     */
7828    protected ContextMenuInfo getContextMenuInfo() {
7829        return null;
7830    }
7831
7832    /**
7833     * Views should implement this if the view itself is going to add items to
7834     * the context menu.
7835     *
7836     * @param menu the context menu to populate
7837     */
7838    protected void onCreateContextMenu(ContextMenu menu) {
7839    }
7840
7841    /**
7842     * Implement this method to handle trackball motion events.  The
7843     * <em>relative</em> movement of the trackball since the last event
7844     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7845     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7846     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7847     * they will often be fractional values, representing the more fine-grained
7848     * movement information available from a trackball).
7849     *
7850     * @param event The motion event.
7851     * @return True if the event was handled, false otherwise.
7852     */
7853    public boolean onTrackballEvent(MotionEvent event) {
7854        return false;
7855    }
7856
7857    /**
7858     * Implement this method to handle generic motion events.
7859     * <p>
7860     * Generic motion events describe joystick movements, mouse hovers, track pad
7861     * touches, scroll wheel movements and other input events.  The
7862     * {@link MotionEvent#getSource() source} of the motion event specifies
7863     * the class of input that was received.  Implementations of this method
7864     * must examine the bits in the source before processing the event.
7865     * The following code example shows how this is done.
7866     * </p><p>
7867     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7868     * are delivered to the view under the pointer.  All other generic motion events are
7869     * delivered to the focused view.
7870     * </p>
7871     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7872     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7873     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7874     *             // process the joystick movement...
7875     *             return true;
7876     *         }
7877     *     }
7878     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7879     *         switch (event.getAction()) {
7880     *             case MotionEvent.ACTION_HOVER_MOVE:
7881     *                 // process the mouse hover movement...
7882     *                 return true;
7883     *             case MotionEvent.ACTION_SCROLL:
7884     *                 // process the scroll wheel movement...
7885     *                 return true;
7886     *         }
7887     *     }
7888     *     return super.onGenericMotionEvent(event);
7889     * }</pre>
7890     *
7891     * @param event The generic motion event being processed.
7892     * @return True if the event was handled, false otherwise.
7893     */
7894    public boolean onGenericMotionEvent(MotionEvent event) {
7895        return false;
7896    }
7897
7898    /**
7899     * Implement this method to handle hover events.
7900     * <p>
7901     * This method is called whenever a pointer is hovering into, over, or out of the
7902     * bounds of a view and the view is not currently being touched.
7903     * Hover events are represented as pointer events with action
7904     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7905     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7906     * </p>
7907     * <ul>
7908     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7909     * when the pointer enters the bounds of the view.</li>
7910     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7911     * when the pointer has already entered the bounds of the view and has moved.</li>
7912     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7913     * when the pointer has exited the bounds of the view or when the pointer is
7914     * about to go down due to a button click, tap, or similar user action that
7915     * causes the view to be touched.</li>
7916     * </ul>
7917     * <p>
7918     * The view should implement this method to return true to indicate that it is
7919     * handling the hover event, such as by changing its drawable state.
7920     * </p><p>
7921     * The default implementation calls {@link #setHovered} to update the hovered state
7922     * of the view when a hover enter or hover exit event is received, if the view
7923     * is enabled and is clickable.  The default implementation also sends hover
7924     * accessibility events.
7925     * </p>
7926     *
7927     * @param event The motion event that describes the hover.
7928     * @return True if the view handled the hover event.
7929     *
7930     * @see #isHovered
7931     * @see #setHovered
7932     * @see #onHoverChanged
7933     */
7934    public boolean onHoverEvent(MotionEvent event) {
7935        // The root view may receive hover (or touch) events that are outside the bounds of
7936        // the window.  This code ensures that we only send accessibility events for
7937        // hovers that are actually within the bounds of the root view.
7938        final int action = event.getActionMasked();
7939        if (!mSendingHoverAccessibilityEvents) {
7940            if ((action == MotionEvent.ACTION_HOVER_ENTER
7941                    || action == MotionEvent.ACTION_HOVER_MOVE)
7942                    && !hasHoveredChild()
7943                    && pointInView(event.getX(), event.getY())) {
7944                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7945                mSendingHoverAccessibilityEvents = true;
7946            }
7947        } else {
7948            if (action == MotionEvent.ACTION_HOVER_EXIT
7949                    || (action == MotionEvent.ACTION_MOVE
7950                            && !pointInView(event.getX(), event.getY()))) {
7951                mSendingHoverAccessibilityEvents = false;
7952                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7953                // If the window does not have input focus we take away accessibility
7954                // focus as soon as the user stop hovering over the view.
7955                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7956                    getViewRootImpl().setAccessibilityFocusedHost(null);
7957                }
7958            }
7959        }
7960
7961        if (isHoverable()) {
7962            switch (action) {
7963                case MotionEvent.ACTION_HOVER_ENTER:
7964                    setHovered(true);
7965                    break;
7966                case MotionEvent.ACTION_HOVER_EXIT:
7967                    setHovered(false);
7968                    break;
7969            }
7970
7971            // Dispatch the event to onGenericMotionEvent before returning true.
7972            // This is to provide compatibility with existing applications that
7973            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7974            // break because of the new default handling for hoverable views
7975            // in onHoverEvent.
7976            // Note that onGenericMotionEvent will be called by default when
7977            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7978            dispatchGenericMotionEventInternal(event);
7979            return true;
7980        }
7981
7982        return false;
7983    }
7984
7985    /**
7986     * Returns true if the view should handle {@link #onHoverEvent}
7987     * by calling {@link #setHovered} to change its hovered state.
7988     *
7989     * @return True if the view is hoverable.
7990     */
7991    private boolean isHoverable() {
7992        final int viewFlags = mViewFlags;
7993        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7994            return false;
7995        }
7996
7997        return (viewFlags & CLICKABLE) == CLICKABLE
7998                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7999    }
8000
8001    /**
8002     * Returns true if the view is currently hovered.
8003     *
8004     * @return True if the view is currently hovered.
8005     *
8006     * @see #setHovered
8007     * @see #onHoverChanged
8008     */
8009    @ViewDebug.ExportedProperty
8010    public boolean isHovered() {
8011        return (mPrivateFlags & HOVERED) != 0;
8012    }
8013
8014    /**
8015     * Sets whether the view is currently hovered.
8016     * <p>
8017     * Calling this method also changes the drawable state of the view.  This
8018     * enables the view to react to hover by using different drawable resources
8019     * to change its appearance.
8020     * </p><p>
8021     * The {@link #onHoverChanged} method is called when the hovered state changes.
8022     * </p>
8023     *
8024     * @param hovered True if the view is hovered.
8025     *
8026     * @see #isHovered
8027     * @see #onHoverChanged
8028     */
8029    public void setHovered(boolean hovered) {
8030        if (hovered) {
8031            if ((mPrivateFlags & HOVERED) == 0) {
8032                mPrivateFlags |= HOVERED;
8033                refreshDrawableState();
8034                onHoverChanged(true);
8035            }
8036        } else {
8037            if ((mPrivateFlags & HOVERED) != 0) {
8038                mPrivateFlags &= ~HOVERED;
8039                refreshDrawableState();
8040                onHoverChanged(false);
8041            }
8042        }
8043    }
8044
8045    /**
8046     * Implement this method to handle hover state changes.
8047     * <p>
8048     * This method is called whenever the hover state changes as a result of a
8049     * call to {@link #setHovered}.
8050     * </p>
8051     *
8052     * @param hovered The current hover state, as returned by {@link #isHovered}.
8053     *
8054     * @see #isHovered
8055     * @see #setHovered
8056     */
8057    public void onHoverChanged(boolean hovered) {
8058    }
8059
8060    /**
8061     * Implement this method to handle touch screen motion events.
8062     *
8063     * @param event The motion event.
8064     * @return True if the event was handled, false otherwise.
8065     */
8066    public boolean onTouchEvent(MotionEvent event) {
8067        final int viewFlags = mViewFlags;
8068
8069        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8070            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
8071                setPressed(false);
8072            }
8073            // A disabled view that is clickable still consumes the touch
8074            // events, it just doesn't respond to them.
8075            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8076                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8077        }
8078
8079        if (mTouchDelegate != null) {
8080            if (mTouchDelegate.onTouchEvent(event)) {
8081                return true;
8082            }
8083        }
8084
8085        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8086                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8087            switch (event.getAction()) {
8088                case MotionEvent.ACTION_UP:
8089                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
8090                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
8091                        // take focus if we don't have it already and we should in
8092                        // touch mode.
8093                        boolean focusTaken = false;
8094                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8095                            focusTaken = requestFocus();
8096                        }
8097
8098                        if (prepressed) {
8099                            // The button is being released before we actually
8100                            // showed it as pressed.  Make it show the pressed
8101                            // state now (before scheduling the click) to ensure
8102                            // the user sees it.
8103                            setPressed(true);
8104                       }
8105
8106                        if (!mHasPerformedLongPress) {
8107                            // This is a tap, so remove the longpress check
8108                            removeLongPressCallback();
8109
8110                            // Only perform take click actions if we were in the pressed state
8111                            if (!focusTaken) {
8112                                // Use a Runnable and post this rather than calling
8113                                // performClick directly. This lets other visual state
8114                                // of the view update before click actions start.
8115                                if (mPerformClick == null) {
8116                                    mPerformClick = new PerformClick();
8117                                }
8118                                if (!post(mPerformClick)) {
8119                                    performClick();
8120                                }
8121                            }
8122                        }
8123
8124                        if (mUnsetPressedState == null) {
8125                            mUnsetPressedState = new UnsetPressedState();
8126                        }
8127
8128                        if (prepressed) {
8129                            postDelayed(mUnsetPressedState,
8130                                    ViewConfiguration.getPressedStateDuration());
8131                        } else if (!post(mUnsetPressedState)) {
8132                            // If the post failed, unpress right now
8133                            mUnsetPressedState.run();
8134                        }
8135                        removeTapCallback();
8136                    }
8137                    break;
8138
8139                case MotionEvent.ACTION_DOWN:
8140                    mHasPerformedLongPress = false;
8141
8142                    if (performButtonActionOnTouchDown(event)) {
8143                        break;
8144                    }
8145
8146                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8147                    boolean isInScrollingContainer = isInScrollingContainer();
8148
8149                    // For views inside a scrolling container, delay the pressed feedback for
8150                    // a short period in case this is a scroll.
8151                    if (isInScrollingContainer) {
8152                        mPrivateFlags |= PREPRESSED;
8153                        if (mPendingCheckForTap == null) {
8154                            mPendingCheckForTap = new CheckForTap();
8155                        }
8156                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8157                    } else {
8158                        // Not inside a scrolling container, so show the feedback right away
8159                        setPressed(true);
8160                        checkForLongClick(0);
8161                    }
8162                    break;
8163
8164                case MotionEvent.ACTION_CANCEL:
8165                    setPressed(false);
8166                    removeTapCallback();
8167                    break;
8168
8169                case MotionEvent.ACTION_MOVE:
8170                    final int x = (int) event.getX();
8171                    final int y = (int) event.getY();
8172
8173                    // Be lenient about moving outside of buttons
8174                    if (!pointInView(x, y, mTouchSlop)) {
8175                        // Outside button
8176                        removeTapCallback();
8177                        if ((mPrivateFlags & PRESSED) != 0) {
8178                            // Remove any future long press/tap checks
8179                            removeLongPressCallback();
8180
8181                            setPressed(false);
8182                        }
8183                    }
8184                    break;
8185            }
8186            return true;
8187        }
8188
8189        return false;
8190    }
8191
8192    /**
8193     * @hide
8194     */
8195    public boolean isInScrollingContainer() {
8196        ViewParent p = getParent();
8197        while (p != null && p instanceof ViewGroup) {
8198            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8199                return true;
8200            }
8201            p = p.getParent();
8202        }
8203        return false;
8204    }
8205
8206    /**
8207     * Remove the longpress detection timer.
8208     */
8209    private void removeLongPressCallback() {
8210        if (mPendingCheckForLongPress != null) {
8211          removeCallbacks(mPendingCheckForLongPress);
8212        }
8213    }
8214
8215    /**
8216     * Remove the pending click action
8217     */
8218    private void removePerformClickCallback() {
8219        if (mPerformClick != null) {
8220            removeCallbacks(mPerformClick);
8221        }
8222    }
8223
8224    /**
8225     * Remove the prepress detection timer.
8226     */
8227    private void removeUnsetPressCallback() {
8228        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
8229            setPressed(false);
8230            removeCallbacks(mUnsetPressedState);
8231        }
8232    }
8233
8234    /**
8235     * Remove the tap detection timer.
8236     */
8237    private void removeTapCallback() {
8238        if (mPendingCheckForTap != null) {
8239            mPrivateFlags &= ~PREPRESSED;
8240            removeCallbacks(mPendingCheckForTap);
8241        }
8242    }
8243
8244    /**
8245     * Cancels a pending long press.  Your subclass can use this if you
8246     * want the context menu to come up if the user presses and holds
8247     * at the same place, but you don't want it to come up if they press
8248     * and then move around enough to cause scrolling.
8249     */
8250    public void cancelLongPress() {
8251        removeLongPressCallback();
8252
8253        /*
8254         * The prepressed state handled by the tap callback is a display
8255         * construct, but the tap callback will post a long press callback
8256         * less its own timeout. Remove it here.
8257         */
8258        removeTapCallback();
8259    }
8260
8261    /**
8262     * Remove the pending callback for sending a
8263     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8264     */
8265    private void removeSendViewScrolledAccessibilityEventCallback() {
8266        if (mSendViewScrolledAccessibilityEvent != null) {
8267            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8268            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8269        }
8270    }
8271
8272    /**
8273     * Sets the TouchDelegate for this View.
8274     */
8275    public void setTouchDelegate(TouchDelegate delegate) {
8276        mTouchDelegate = delegate;
8277    }
8278
8279    /**
8280     * Gets the TouchDelegate for this View.
8281     */
8282    public TouchDelegate getTouchDelegate() {
8283        return mTouchDelegate;
8284    }
8285
8286    /**
8287     * Set flags controlling behavior of this view.
8288     *
8289     * @param flags Constant indicating the value which should be set
8290     * @param mask Constant indicating the bit range that should be changed
8291     */
8292    void setFlags(int flags, int mask) {
8293        int old = mViewFlags;
8294        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8295
8296        int changed = mViewFlags ^ old;
8297        if (changed == 0) {
8298            return;
8299        }
8300        int privateFlags = mPrivateFlags;
8301
8302        /* Check if the FOCUSABLE bit has changed */
8303        if (((changed & FOCUSABLE_MASK) != 0) &&
8304                ((privateFlags & HAS_BOUNDS) !=0)) {
8305            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8306                    && ((privateFlags & FOCUSED) != 0)) {
8307                /* Give up focus if we are no longer focusable */
8308                clearFocus();
8309            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8310                    && ((privateFlags & FOCUSED) == 0)) {
8311                /*
8312                 * Tell the view system that we are now available to take focus
8313                 * if no one else already has it.
8314                 */
8315                if (mParent != null) mParent.focusableViewAvailable(this);
8316            }
8317            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8318                notifyAccessibilityStateChanged();
8319            }
8320        }
8321
8322        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8323            if ((changed & VISIBILITY_MASK) != 0) {
8324                /*
8325                 * If this view is becoming visible, invalidate it in case it changed while
8326                 * it was not visible. Marking it drawn ensures that the invalidation will
8327                 * go through.
8328                 */
8329                mPrivateFlags |= DRAWN;
8330                invalidate(true);
8331
8332                needGlobalAttributesUpdate(true);
8333
8334                // a view becoming visible is worth notifying the parent
8335                // about in case nothing has focus.  even if this specific view
8336                // isn't focusable, it may contain something that is, so let
8337                // the root view try to give this focus if nothing else does.
8338                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8339                    mParent.focusableViewAvailable(this);
8340                }
8341            }
8342        }
8343
8344        /* Check if the GONE bit has changed */
8345        if ((changed & GONE) != 0) {
8346            needGlobalAttributesUpdate(false);
8347            requestLayout();
8348
8349            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8350                if (hasFocus()) clearFocus();
8351                clearAccessibilityFocus();
8352                destroyDrawingCache();
8353                if (mParent instanceof View) {
8354                    // GONE views noop invalidation, so invalidate the parent
8355                    ((View) mParent).invalidate(true);
8356                }
8357                // Mark the view drawn to ensure that it gets invalidated properly the next
8358                // time it is visible and gets invalidated
8359                mPrivateFlags |= DRAWN;
8360            }
8361            if (mAttachInfo != null) {
8362                mAttachInfo.mViewVisibilityChanged = true;
8363            }
8364        }
8365
8366        /* Check if the VISIBLE bit has changed */
8367        if ((changed & INVISIBLE) != 0) {
8368            needGlobalAttributesUpdate(false);
8369            /*
8370             * If this view is becoming invisible, set the DRAWN flag so that
8371             * the next invalidate() will not be skipped.
8372             */
8373            mPrivateFlags |= DRAWN;
8374
8375            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8376                // root view becoming invisible shouldn't clear focus and accessibility focus
8377                if (getRootView() != this) {
8378                    clearFocus();
8379                    clearAccessibilityFocus();
8380                }
8381            }
8382            if (mAttachInfo != null) {
8383                mAttachInfo.mViewVisibilityChanged = true;
8384            }
8385        }
8386
8387        if ((changed & VISIBILITY_MASK) != 0) {
8388            if (mParent instanceof ViewGroup) {
8389                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8390                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8391                ((View) mParent).invalidate(true);
8392            } else if (mParent != null) {
8393                mParent.invalidateChild(this, null);
8394            }
8395            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8396        }
8397
8398        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8399            destroyDrawingCache();
8400        }
8401
8402        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8403            destroyDrawingCache();
8404            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8405            invalidateParentCaches();
8406        }
8407
8408        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8409            destroyDrawingCache();
8410            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8411        }
8412
8413        if ((changed & DRAW_MASK) != 0) {
8414            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8415                if (mBackground != null) {
8416                    mPrivateFlags &= ~SKIP_DRAW;
8417                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8418                } else {
8419                    mPrivateFlags |= SKIP_DRAW;
8420                }
8421            } else {
8422                mPrivateFlags &= ~SKIP_DRAW;
8423            }
8424            requestLayout();
8425            invalidate(true);
8426        }
8427
8428        if ((changed & KEEP_SCREEN_ON) != 0) {
8429            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8430                mParent.recomputeViewAttributes(this);
8431            }
8432        }
8433
8434        if (AccessibilityManager.getInstance(mContext).isEnabled()
8435                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8436                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8437            notifyAccessibilityStateChanged();
8438        }
8439    }
8440
8441    /**
8442     * Change the view's z order in the tree, so it's on top of other sibling
8443     * views
8444     */
8445    public void bringToFront() {
8446        if (mParent != null) {
8447            mParent.bringChildToFront(this);
8448        }
8449    }
8450
8451    /**
8452     * This is called in response to an internal scroll in this view (i.e., the
8453     * view scrolled its own contents). This is typically as a result of
8454     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8455     * called.
8456     *
8457     * @param l Current horizontal scroll origin.
8458     * @param t Current vertical scroll origin.
8459     * @param oldl Previous horizontal scroll origin.
8460     * @param oldt Previous vertical scroll origin.
8461     */
8462    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8463        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8464            postSendViewScrolledAccessibilityEventCallback();
8465        }
8466
8467        mBackgroundSizeChanged = true;
8468
8469        final AttachInfo ai = mAttachInfo;
8470        if (ai != null) {
8471            ai.mViewScrollChanged = true;
8472        }
8473    }
8474
8475    /**
8476     * Interface definition for a callback to be invoked when the layout bounds of a view
8477     * changes due to layout processing.
8478     */
8479    public interface OnLayoutChangeListener {
8480        /**
8481         * Called when the focus state of a view has changed.
8482         *
8483         * @param v The view whose state has changed.
8484         * @param left The new value of the view's left property.
8485         * @param top The new value of the view's top property.
8486         * @param right The new value of the view's right property.
8487         * @param bottom The new value of the view's bottom property.
8488         * @param oldLeft The previous value of the view's left property.
8489         * @param oldTop The previous value of the view's top property.
8490         * @param oldRight The previous value of the view's right property.
8491         * @param oldBottom The previous value of the view's bottom property.
8492         */
8493        void onLayoutChange(View v, int left, int top, int right, int bottom,
8494            int oldLeft, int oldTop, int oldRight, int oldBottom);
8495    }
8496
8497    /**
8498     * This is called during layout when the size of this view has changed. If
8499     * you were just added to the view hierarchy, you're called with the old
8500     * values of 0.
8501     *
8502     * @param w Current width of this view.
8503     * @param h Current height of this view.
8504     * @param oldw Old width of this view.
8505     * @param oldh Old height of this view.
8506     */
8507    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8508    }
8509
8510    /**
8511     * Called by draw to draw the child views. This may be overridden
8512     * by derived classes to gain control just before its children are drawn
8513     * (but after its own view has been drawn).
8514     * @param canvas the canvas on which to draw the view
8515     */
8516    protected void dispatchDraw(Canvas canvas) {
8517
8518    }
8519
8520    /**
8521     * Gets the parent of this view. Note that the parent is a
8522     * ViewParent and not necessarily a View.
8523     *
8524     * @return Parent of this view.
8525     */
8526    public final ViewParent getParent() {
8527        return mParent;
8528    }
8529
8530    /**
8531     * Set the horizontal scrolled position of your view. This will cause a call to
8532     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8533     * invalidated.
8534     * @param value the x position to scroll to
8535     */
8536    public void setScrollX(int value) {
8537        scrollTo(value, mScrollY);
8538    }
8539
8540    /**
8541     * Set the vertical scrolled position of your view. This will cause a call to
8542     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8543     * invalidated.
8544     * @param value the y position to scroll to
8545     */
8546    public void setScrollY(int value) {
8547        scrollTo(mScrollX, value);
8548    }
8549
8550    /**
8551     * Return the scrolled left position of this view. This is the left edge of
8552     * the displayed part of your view. You do not need to draw any pixels
8553     * farther left, since those are outside of the frame of your view on
8554     * screen.
8555     *
8556     * @return The left edge of the displayed part of your view, in pixels.
8557     */
8558    public final int getScrollX() {
8559        return mScrollX;
8560    }
8561
8562    /**
8563     * Return the scrolled top position of this view. This is the top edge of
8564     * the displayed part of your view. You do not need to draw any pixels above
8565     * it, since those are outside of the frame of your view on screen.
8566     *
8567     * @return The top edge of the displayed part of your view, in pixels.
8568     */
8569    public final int getScrollY() {
8570        return mScrollY;
8571    }
8572
8573    /**
8574     * Return the width of the your view.
8575     *
8576     * @return The width of your view, in pixels.
8577     */
8578    @ViewDebug.ExportedProperty(category = "layout")
8579    public final int getWidth() {
8580        return mRight - mLeft;
8581    }
8582
8583    /**
8584     * Return the height of your view.
8585     *
8586     * @return The height of your view, in pixels.
8587     */
8588    @ViewDebug.ExportedProperty(category = "layout")
8589    public final int getHeight() {
8590        return mBottom - mTop;
8591    }
8592
8593    /**
8594     * Return the visible drawing bounds of your view. Fills in the output
8595     * rectangle with the values from getScrollX(), getScrollY(),
8596     * getWidth(), and getHeight().
8597     *
8598     * @param outRect The (scrolled) drawing bounds of the view.
8599     */
8600    public void getDrawingRect(Rect outRect) {
8601        outRect.left = mScrollX;
8602        outRect.top = mScrollY;
8603        outRect.right = mScrollX + (mRight - mLeft);
8604        outRect.bottom = mScrollY + (mBottom - mTop);
8605    }
8606
8607    /**
8608     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8609     * raw width component (that is the result is masked by
8610     * {@link #MEASURED_SIZE_MASK}).
8611     *
8612     * @return The raw measured width of this view.
8613     */
8614    public final int getMeasuredWidth() {
8615        return mMeasuredWidth & MEASURED_SIZE_MASK;
8616    }
8617
8618    /**
8619     * Return the full width measurement information for this view as computed
8620     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8621     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8622     * This should be used during measurement and layout calculations only. Use
8623     * {@link #getWidth()} to see how wide a view is after layout.
8624     *
8625     * @return The measured width of this view as a bit mask.
8626     */
8627    public final int getMeasuredWidthAndState() {
8628        return mMeasuredWidth;
8629    }
8630
8631    /**
8632     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8633     * raw width component (that is the result is masked by
8634     * {@link #MEASURED_SIZE_MASK}).
8635     *
8636     * @return The raw measured height of this view.
8637     */
8638    public final int getMeasuredHeight() {
8639        return mMeasuredHeight & MEASURED_SIZE_MASK;
8640    }
8641
8642    /**
8643     * Return the full height measurement information for this view as computed
8644     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8645     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8646     * This should be used during measurement and layout calculations only. Use
8647     * {@link #getHeight()} to see how wide a view is after layout.
8648     *
8649     * @return The measured width of this view as a bit mask.
8650     */
8651    public final int getMeasuredHeightAndState() {
8652        return mMeasuredHeight;
8653    }
8654
8655    /**
8656     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8657     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8658     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8659     * and the height component is at the shifted bits
8660     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8661     */
8662    public final int getMeasuredState() {
8663        return (mMeasuredWidth&MEASURED_STATE_MASK)
8664                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8665                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8666    }
8667
8668    /**
8669     * The transform matrix of this view, which is calculated based on the current
8670     * roation, scale, and pivot properties.
8671     *
8672     * @see #getRotation()
8673     * @see #getScaleX()
8674     * @see #getScaleY()
8675     * @see #getPivotX()
8676     * @see #getPivotY()
8677     * @return The current transform matrix for the view
8678     */
8679    public Matrix getMatrix() {
8680        if (mTransformationInfo != null) {
8681            updateMatrix();
8682            return mTransformationInfo.mMatrix;
8683        }
8684        return Matrix.IDENTITY_MATRIX;
8685    }
8686
8687    /**
8688     * Utility function to determine if the value is far enough away from zero to be
8689     * considered non-zero.
8690     * @param value A floating point value to check for zero-ness
8691     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8692     */
8693    private static boolean nonzero(float value) {
8694        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8695    }
8696
8697    /**
8698     * Returns true if the transform matrix is the identity matrix.
8699     * Recomputes the matrix if necessary.
8700     *
8701     * @return True if the transform matrix is the identity matrix, false otherwise.
8702     */
8703    final boolean hasIdentityMatrix() {
8704        if (mTransformationInfo != null) {
8705            updateMatrix();
8706            return mTransformationInfo.mMatrixIsIdentity;
8707        }
8708        return true;
8709    }
8710
8711    void ensureTransformationInfo() {
8712        if (mTransformationInfo == null) {
8713            mTransformationInfo = new TransformationInfo();
8714        }
8715    }
8716
8717    /**
8718     * Recomputes the transform matrix if necessary.
8719     */
8720    private void updateMatrix() {
8721        final TransformationInfo info = mTransformationInfo;
8722        if (info == null) {
8723            return;
8724        }
8725        if (info.mMatrixDirty) {
8726            // transform-related properties have changed since the last time someone
8727            // asked for the matrix; recalculate it with the current values
8728
8729            // Figure out if we need to update the pivot point
8730            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8731                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8732                    info.mPrevWidth = mRight - mLeft;
8733                    info.mPrevHeight = mBottom - mTop;
8734                    info.mPivotX = info.mPrevWidth / 2f;
8735                    info.mPivotY = info.mPrevHeight / 2f;
8736                }
8737            }
8738            info.mMatrix.reset();
8739            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8740                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8741                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8742                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8743            } else {
8744                if (info.mCamera == null) {
8745                    info.mCamera = new Camera();
8746                    info.matrix3D = new Matrix();
8747                }
8748                info.mCamera.save();
8749                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8750                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8751                info.mCamera.getMatrix(info.matrix3D);
8752                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8753                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8754                        info.mPivotY + info.mTranslationY);
8755                info.mMatrix.postConcat(info.matrix3D);
8756                info.mCamera.restore();
8757            }
8758            info.mMatrixDirty = false;
8759            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8760            info.mInverseMatrixDirty = true;
8761        }
8762    }
8763
8764    /**
8765     * Utility method to retrieve the inverse of the current mMatrix property.
8766     * We cache the matrix to avoid recalculating it when transform properties
8767     * have not changed.
8768     *
8769     * @return The inverse of the current matrix of this view.
8770     */
8771    final Matrix getInverseMatrix() {
8772        final TransformationInfo info = mTransformationInfo;
8773        if (info != null) {
8774            updateMatrix();
8775            if (info.mInverseMatrixDirty) {
8776                if (info.mInverseMatrix == null) {
8777                    info.mInverseMatrix = new Matrix();
8778                }
8779                info.mMatrix.invert(info.mInverseMatrix);
8780                info.mInverseMatrixDirty = false;
8781            }
8782            return info.mInverseMatrix;
8783        }
8784        return Matrix.IDENTITY_MATRIX;
8785    }
8786
8787    /**
8788     * Gets the distance along the Z axis from the camera to this view.
8789     *
8790     * @see #setCameraDistance(float)
8791     *
8792     * @return The distance along the Z axis.
8793     */
8794    public float getCameraDistance() {
8795        ensureTransformationInfo();
8796        final float dpi = mResources.getDisplayMetrics().densityDpi;
8797        final TransformationInfo info = mTransformationInfo;
8798        if (info.mCamera == null) {
8799            info.mCamera = new Camera();
8800            info.matrix3D = new Matrix();
8801        }
8802        return -(info.mCamera.getLocationZ() * dpi);
8803    }
8804
8805    /**
8806     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8807     * views are drawn) from the camera to this view. The camera's distance
8808     * affects 3D transformations, for instance rotations around the X and Y
8809     * axis. If the rotationX or rotationY properties are changed and this view is
8810     * large (more than half the size of the screen), it is recommended to always
8811     * use a camera distance that's greater than the height (X axis rotation) or
8812     * the width (Y axis rotation) of this view.</p>
8813     *
8814     * <p>The distance of the camera from the view plane can have an affect on the
8815     * perspective distortion of the view when it is rotated around the x or y axis.
8816     * For example, a large distance will result in a large viewing angle, and there
8817     * will not be much perspective distortion of the view as it rotates. A short
8818     * distance may cause much more perspective distortion upon rotation, and can
8819     * also result in some drawing artifacts if the rotated view ends up partially
8820     * behind the camera (which is why the recommendation is to use a distance at
8821     * least as far as the size of the view, if the view is to be rotated.)</p>
8822     *
8823     * <p>The distance is expressed in "depth pixels." The default distance depends
8824     * on the screen density. For instance, on a medium density display, the
8825     * default distance is 1280. On a high density display, the default distance
8826     * is 1920.</p>
8827     *
8828     * <p>If you want to specify a distance that leads to visually consistent
8829     * results across various densities, use the following formula:</p>
8830     * <pre>
8831     * float scale = context.getResources().getDisplayMetrics().density;
8832     * view.setCameraDistance(distance * scale);
8833     * </pre>
8834     *
8835     * <p>The density scale factor of a high density display is 1.5,
8836     * and 1920 = 1280 * 1.5.</p>
8837     *
8838     * @param distance The distance in "depth pixels", if negative the opposite
8839     *        value is used
8840     *
8841     * @see #setRotationX(float)
8842     * @see #setRotationY(float)
8843     */
8844    public void setCameraDistance(float distance) {
8845        invalidateViewProperty(true, false);
8846
8847        ensureTransformationInfo();
8848        final float dpi = mResources.getDisplayMetrics().densityDpi;
8849        final TransformationInfo info = mTransformationInfo;
8850        if (info.mCamera == null) {
8851            info.mCamera = new Camera();
8852            info.matrix3D = new Matrix();
8853        }
8854
8855        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8856        info.mMatrixDirty = true;
8857
8858        invalidateViewProperty(false, false);
8859        if (mDisplayList != null) {
8860            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8861        }
8862        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8863            // View was rejected last time it was drawn by its parent; this may have changed
8864            invalidateParentIfNeeded();
8865        }
8866    }
8867
8868    /**
8869     * The degrees that the view is rotated around the pivot point.
8870     *
8871     * @see #setRotation(float)
8872     * @see #getPivotX()
8873     * @see #getPivotY()
8874     *
8875     * @return The degrees of rotation.
8876     */
8877    @ViewDebug.ExportedProperty(category = "drawing")
8878    public float getRotation() {
8879        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8880    }
8881
8882    /**
8883     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8884     * result in clockwise rotation.
8885     *
8886     * @param rotation The degrees of rotation.
8887     *
8888     * @see #getRotation()
8889     * @see #getPivotX()
8890     * @see #getPivotY()
8891     * @see #setRotationX(float)
8892     * @see #setRotationY(float)
8893     *
8894     * @attr ref android.R.styleable#View_rotation
8895     */
8896    public void setRotation(float rotation) {
8897        ensureTransformationInfo();
8898        final TransformationInfo info = mTransformationInfo;
8899        if (info.mRotation != rotation) {
8900            // Double-invalidation is necessary to capture view's old and new areas
8901            invalidateViewProperty(true, false);
8902            info.mRotation = rotation;
8903            info.mMatrixDirty = true;
8904            invalidateViewProperty(false, true);
8905            if (mDisplayList != null) {
8906                mDisplayList.setRotation(rotation);
8907            }
8908            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8909                // View was rejected last time it was drawn by its parent; this may have changed
8910                invalidateParentIfNeeded();
8911            }
8912        }
8913    }
8914
8915    /**
8916     * The degrees that the view is rotated around the vertical axis through the pivot point.
8917     *
8918     * @see #getPivotX()
8919     * @see #getPivotY()
8920     * @see #setRotationY(float)
8921     *
8922     * @return The degrees of Y rotation.
8923     */
8924    @ViewDebug.ExportedProperty(category = "drawing")
8925    public float getRotationY() {
8926        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8927    }
8928
8929    /**
8930     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8931     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8932     * down the y axis.
8933     *
8934     * When rotating large views, it is recommended to adjust the camera distance
8935     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8936     *
8937     * @param rotationY The degrees of Y rotation.
8938     *
8939     * @see #getRotationY()
8940     * @see #getPivotX()
8941     * @see #getPivotY()
8942     * @see #setRotation(float)
8943     * @see #setRotationX(float)
8944     * @see #setCameraDistance(float)
8945     *
8946     * @attr ref android.R.styleable#View_rotationY
8947     */
8948    public void setRotationY(float rotationY) {
8949        ensureTransformationInfo();
8950        final TransformationInfo info = mTransformationInfo;
8951        if (info.mRotationY != rotationY) {
8952            invalidateViewProperty(true, false);
8953            info.mRotationY = rotationY;
8954            info.mMatrixDirty = true;
8955            invalidateViewProperty(false, true);
8956            if (mDisplayList != null) {
8957                mDisplayList.setRotationY(rotationY);
8958            }
8959            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8960                // View was rejected last time it was drawn by its parent; this may have changed
8961                invalidateParentIfNeeded();
8962            }
8963        }
8964    }
8965
8966    /**
8967     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8968     *
8969     * @see #getPivotX()
8970     * @see #getPivotY()
8971     * @see #setRotationX(float)
8972     *
8973     * @return The degrees of X rotation.
8974     */
8975    @ViewDebug.ExportedProperty(category = "drawing")
8976    public float getRotationX() {
8977        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8978    }
8979
8980    /**
8981     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8982     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8983     * x axis.
8984     *
8985     * When rotating large views, it is recommended to adjust the camera distance
8986     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8987     *
8988     * @param rotationX The degrees of X rotation.
8989     *
8990     * @see #getRotationX()
8991     * @see #getPivotX()
8992     * @see #getPivotY()
8993     * @see #setRotation(float)
8994     * @see #setRotationY(float)
8995     * @see #setCameraDistance(float)
8996     *
8997     * @attr ref android.R.styleable#View_rotationX
8998     */
8999    public void setRotationX(float rotationX) {
9000        ensureTransformationInfo();
9001        final TransformationInfo info = mTransformationInfo;
9002        if (info.mRotationX != rotationX) {
9003            invalidateViewProperty(true, false);
9004            info.mRotationX = rotationX;
9005            info.mMatrixDirty = true;
9006            invalidateViewProperty(false, true);
9007            if (mDisplayList != null) {
9008                mDisplayList.setRotationX(rotationX);
9009            }
9010            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9011                // View was rejected last time it was drawn by its parent; this may have changed
9012                invalidateParentIfNeeded();
9013            }
9014        }
9015    }
9016
9017    /**
9018     * The amount that the view is scaled in x around the pivot point, as a proportion of
9019     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9020     *
9021     * <p>By default, this is 1.0f.
9022     *
9023     * @see #getPivotX()
9024     * @see #getPivotY()
9025     * @return The scaling factor.
9026     */
9027    @ViewDebug.ExportedProperty(category = "drawing")
9028    public float getScaleX() {
9029        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9030    }
9031
9032    /**
9033     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9034     * the view's unscaled width. A value of 1 means that no scaling is applied.
9035     *
9036     * @param scaleX The scaling factor.
9037     * @see #getPivotX()
9038     * @see #getPivotY()
9039     *
9040     * @attr ref android.R.styleable#View_scaleX
9041     */
9042    public void setScaleX(float scaleX) {
9043        ensureTransformationInfo();
9044        final TransformationInfo info = mTransformationInfo;
9045        if (info.mScaleX != scaleX) {
9046            invalidateViewProperty(true, false);
9047            info.mScaleX = scaleX;
9048            info.mMatrixDirty = true;
9049            invalidateViewProperty(false, true);
9050            if (mDisplayList != null) {
9051                mDisplayList.setScaleX(scaleX);
9052            }
9053            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9054                // View was rejected last time it was drawn by its parent; this may have changed
9055                invalidateParentIfNeeded();
9056            }
9057        }
9058    }
9059
9060    /**
9061     * The amount that the view is scaled in y around the pivot point, as a proportion of
9062     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9063     *
9064     * <p>By default, this is 1.0f.
9065     *
9066     * @see #getPivotX()
9067     * @see #getPivotY()
9068     * @return The scaling factor.
9069     */
9070    @ViewDebug.ExportedProperty(category = "drawing")
9071    public float getScaleY() {
9072        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9073    }
9074
9075    /**
9076     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9077     * the view's unscaled width. A value of 1 means that no scaling is applied.
9078     *
9079     * @param scaleY The scaling factor.
9080     * @see #getPivotX()
9081     * @see #getPivotY()
9082     *
9083     * @attr ref android.R.styleable#View_scaleY
9084     */
9085    public void setScaleY(float scaleY) {
9086        ensureTransformationInfo();
9087        final TransformationInfo info = mTransformationInfo;
9088        if (info.mScaleY != scaleY) {
9089            invalidateViewProperty(true, false);
9090            info.mScaleY = scaleY;
9091            info.mMatrixDirty = true;
9092            invalidateViewProperty(false, true);
9093            if (mDisplayList != null) {
9094                mDisplayList.setScaleY(scaleY);
9095            }
9096            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9097                // View was rejected last time it was drawn by its parent; this may have changed
9098                invalidateParentIfNeeded();
9099            }
9100        }
9101    }
9102
9103    /**
9104     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9105     * and {@link #setScaleX(float) scaled}.
9106     *
9107     * @see #getRotation()
9108     * @see #getScaleX()
9109     * @see #getScaleY()
9110     * @see #getPivotY()
9111     * @return The x location of the pivot point.
9112     *
9113     * @attr ref android.R.styleable#View_transformPivotX
9114     */
9115    @ViewDebug.ExportedProperty(category = "drawing")
9116    public float getPivotX() {
9117        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9118    }
9119
9120    /**
9121     * Sets the x location of the point around which the view is
9122     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9123     * By default, the pivot point is centered on the object.
9124     * Setting this property disables this behavior and causes the view to use only the
9125     * explicitly set pivotX and pivotY values.
9126     *
9127     * @param pivotX The x location of the pivot point.
9128     * @see #getRotation()
9129     * @see #getScaleX()
9130     * @see #getScaleY()
9131     * @see #getPivotY()
9132     *
9133     * @attr ref android.R.styleable#View_transformPivotX
9134     */
9135    public void setPivotX(float pivotX) {
9136        ensureTransformationInfo();
9137        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
9138        final TransformationInfo info = mTransformationInfo;
9139        if (info.mPivotX != pivotX) {
9140            invalidateViewProperty(true, false);
9141            info.mPivotX = pivotX;
9142            info.mMatrixDirty = true;
9143            invalidateViewProperty(false, true);
9144            if (mDisplayList != null) {
9145                mDisplayList.setPivotX(pivotX);
9146            }
9147            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9148                // View was rejected last time it was drawn by its parent; this may have changed
9149                invalidateParentIfNeeded();
9150            }
9151        }
9152    }
9153
9154    /**
9155     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9156     * and {@link #setScaleY(float) scaled}.
9157     *
9158     * @see #getRotation()
9159     * @see #getScaleX()
9160     * @see #getScaleY()
9161     * @see #getPivotY()
9162     * @return The y location of the pivot point.
9163     *
9164     * @attr ref android.R.styleable#View_transformPivotY
9165     */
9166    @ViewDebug.ExportedProperty(category = "drawing")
9167    public float getPivotY() {
9168        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9169    }
9170
9171    /**
9172     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9173     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9174     * Setting this property disables this behavior and causes the view to use only the
9175     * explicitly set pivotX and pivotY values.
9176     *
9177     * @param pivotY The y location of the pivot point.
9178     * @see #getRotation()
9179     * @see #getScaleX()
9180     * @see #getScaleY()
9181     * @see #getPivotY()
9182     *
9183     * @attr ref android.R.styleable#View_transformPivotY
9184     */
9185    public void setPivotY(float pivotY) {
9186        ensureTransformationInfo();
9187        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
9188        final TransformationInfo info = mTransformationInfo;
9189        if (info.mPivotY != pivotY) {
9190            invalidateViewProperty(true, false);
9191            info.mPivotY = pivotY;
9192            info.mMatrixDirty = true;
9193            invalidateViewProperty(false, true);
9194            if (mDisplayList != null) {
9195                mDisplayList.setPivotY(pivotY);
9196            }
9197            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9198                // View was rejected last time it was drawn by its parent; this may have changed
9199                invalidateParentIfNeeded();
9200            }
9201        }
9202    }
9203
9204    /**
9205     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9206     * completely transparent and 1 means the view is completely opaque.
9207     *
9208     * <p>By default this is 1.0f.
9209     * @return The opacity of the view.
9210     */
9211    @ViewDebug.ExportedProperty(category = "drawing")
9212    public float getAlpha() {
9213        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9214    }
9215
9216    /**
9217     * Returns whether this View has content which overlaps. This function, intended to be
9218     * overridden by specific View types, is an optimization when alpha is set on a view. If
9219     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9220     * and then composited it into place, which can be expensive. If the view has no overlapping
9221     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9222     * An example of overlapping rendering is a TextView with a background image, such as a
9223     * Button. An example of non-overlapping rendering is a TextView with no background, or
9224     * an ImageView with only the foreground image. The default implementation returns true;
9225     * subclasses should override if they have cases which can be optimized.
9226     *
9227     * @return true if the content in this view might overlap, false otherwise.
9228     */
9229    public boolean hasOverlappingRendering() {
9230        return true;
9231    }
9232
9233    /**
9234     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9235     * completely transparent and 1 means the view is completely opaque.</p>
9236     *
9237     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9238     * responsible for applying the opacity itself. Otherwise, calling this method is
9239     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
9240     * setting a hardware layer.</p>
9241     *
9242     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
9243     * performance implications. It is generally best to use the alpha property sparingly and
9244     * transiently, as in the case of fading animations.</p>
9245     *
9246     * @param alpha The opacity of the view.
9247     *
9248     * @see #setLayerType(int, android.graphics.Paint)
9249     *
9250     * @attr ref android.R.styleable#View_alpha
9251     */
9252    public void setAlpha(float alpha) {
9253        ensureTransformationInfo();
9254        if (mTransformationInfo.mAlpha != alpha) {
9255            mTransformationInfo.mAlpha = alpha;
9256            if (onSetAlpha((int) (alpha * 255))) {
9257                mPrivateFlags |= ALPHA_SET;
9258                // subclass is handling alpha - don't optimize rendering cache invalidation
9259                invalidateParentCaches();
9260                invalidate(true);
9261            } else {
9262                mPrivateFlags &= ~ALPHA_SET;
9263                invalidateViewProperty(true, false);
9264                if (mDisplayList != null) {
9265                    mDisplayList.setAlpha(alpha);
9266                }
9267            }
9268        }
9269    }
9270
9271    /**
9272     * Faster version of setAlpha() which performs the same steps except there are
9273     * no calls to invalidate(). The caller of this function should perform proper invalidation
9274     * on the parent and this object. The return value indicates whether the subclass handles
9275     * alpha (the return value for onSetAlpha()).
9276     *
9277     * @param alpha The new value for the alpha property
9278     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9279     *         the new value for the alpha property is different from the old value
9280     */
9281    boolean setAlphaNoInvalidation(float alpha) {
9282        ensureTransformationInfo();
9283        if (mTransformationInfo.mAlpha != alpha) {
9284            mTransformationInfo.mAlpha = alpha;
9285            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9286            if (subclassHandlesAlpha) {
9287                mPrivateFlags |= ALPHA_SET;
9288                return true;
9289            } else {
9290                mPrivateFlags &= ~ALPHA_SET;
9291                if (mDisplayList != null) {
9292                    mDisplayList.setAlpha(alpha);
9293                }
9294            }
9295        }
9296        return false;
9297    }
9298
9299    /**
9300     * Top position of this view relative to its parent.
9301     *
9302     * @return The top of this view, in pixels.
9303     */
9304    @ViewDebug.CapturedViewProperty
9305    public final int getTop() {
9306        return mTop;
9307    }
9308
9309    /**
9310     * Sets the top position of this view relative to its parent. This method is meant to be called
9311     * by the layout system and should not generally be called otherwise, because the property
9312     * may be changed at any time by the layout.
9313     *
9314     * @param top The top of this view, in pixels.
9315     */
9316    public final void setTop(int top) {
9317        if (top != mTop) {
9318            updateMatrix();
9319            final boolean matrixIsIdentity = mTransformationInfo == null
9320                    || mTransformationInfo.mMatrixIsIdentity;
9321            if (matrixIsIdentity) {
9322                if (mAttachInfo != null) {
9323                    int minTop;
9324                    int yLoc;
9325                    if (top < mTop) {
9326                        minTop = top;
9327                        yLoc = top - mTop;
9328                    } else {
9329                        minTop = mTop;
9330                        yLoc = 0;
9331                    }
9332                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9333                }
9334            } else {
9335                // Double-invalidation is necessary to capture view's old and new areas
9336                invalidate(true);
9337            }
9338
9339            int width = mRight - mLeft;
9340            int oldHeight = mBottom - mTop;
9341
9342            mTop = top;
9343            if (mDisplayList != null) {
9344                mDisplayList.setTop(mTop);
9345            }
9346
9347            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9348
9349            if (!matrixIsIdentity) {
9350                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9351                    // A change in dimension means an auto-centered pivot point changes, too
9352                    mTransformationInfo.mMatrixDirty = true;
9353                }
9354                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9355                invalidate(true);
9356            }
9357            mBackgroundSizeChanged = true;
9358            invalidateParentIfNeeded();
9359            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9360                // View was rejected last time it was drawn by its parent; this may have changed
9361                invalidateParentIfNeeded();
9362            }
9363        }
9364    }
9365
9366    /**
9367     * Bottom position of this view relative to its parent.
9368     *
9369     * @return The bottom of this view, in pixels.
9370     */
9371    @ViewDebug.CapturedViewProperty
9372    public final int getBottom() {
9373        return mBottom;
9374    }
9375
9376    /**
9377     * True if this view has changed since the last time being drawn.
9378     *
9379     * @return The dirty state of this view.
9380     */
9381    public boolean isDirty() {
9382        return (mPrivateFlags & DIRTY_MASK) != 0;
9383    }
9384
9385    /**
9386     * Sets the bottom position of this view relative to its parent. This method is meant to be
9387     * called by the layout system and should not generally be called otherwise, because the
9388     * property may be changed at any time by the layout.
9389     *
9390     * @param bottom The bottom of this view, in pixels.
9391     */
9392    public final void setBottom(int bottom) {
9393        if (bottom != mBottom) {
9394            updateMatrix();
9395            final boolean matrixIsIdentity = mTransformationInfo == null
9396                    || mTransformationInfo.mMatrixIsIdentity;
9397            if (matrixIsIdentity) {
9398                if (mAttachInfo != null) {
9399                    int maxBottom;
9400                    if (bottom < mBottom) {
9401                        maxBottom = mBottom;
9402                    } else {
9403                        maxBottom = bottom;
9404                    }
9405                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9406                }
9407            } else {
9408                // Double-invalidation is necessary to capture view's old and new areas
9409                invalidate(true);
9410            }
9411
9412            int width = mRight - mLeft;
9413            int oldHeight = mBottom - mTop;
9414
9415            mBottom = bottom;
9416            if (mDisplayList != null) {
9417                mDisplayList.setBottom(mBottom);
9418            }
9419
9420            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9421
9422            if (!matrixIsIdentity) {
9423                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9424                    // A change in dimension means an auto-centered pivot point changes, too
9425                    mTransformationInfo.mMatrixDirty = true;
9426                }
9427                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9428                invalidate(true);
9429            }
9430            mBackgroundSizeChanged = true;
9431            invalidateParentIfNeeded();
9432            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9433                // View was rejected last time it was drawn by its parent; this may have changed
9434                invalidateParentIfNeeded();
9435            }
9436        }
9437    }
9438
9439    /**
9440     * Left position of this view relative to its parent.
9441     *
9442     * @return The left edge of this view, in pixels.
9443     */
9444    @ViewDebug.CapturedViewProperty
9445    public final int getLeft() {
9446        return mLeft;
9447    }
9448
9449    /**
9450     * Sets the left position of this view relative to its parent. This method is meant to be called
9451     * by the layout system and should not generally be called otherwise, because the property
9452     * may be changed at any time by the layout.
9453     *
9454     * @param left The bottom of this view, in pixels.
9455     */
9456    public final void setLeft(int left) {
9457        if (left != mLeft) {
9458            updateMatrix();
9459            final boolean matrixIsIdentity = mTransformationInfo == null
9460                    || mTransformationInfo.mMatrixIsIdentity;
9461            if (matrixIsIdentity) {
9462                if (mAttachInfo != null) {
9463                    int minLeft;
9464                    int xLoc;
9465                    if (left < mLeft) {
9466                        minLeft = left;
9467                        xLoc = left - mLeft;
9468                    } else {
9469                        minLeft = mLeft;
9470                        xLoc = 0;
9471                    }
9472                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9473                }
9474            } else {
9475                // Double-invalidation is necessary to capture view's old and new areas
9476                invalidate(true);
9477            }
9478
9479            int oldWidth = mRight - mLeft;
9480            int height = mBottom - mTop;
9481
9482            mLeft = left;
9483            if (mDisplayList != null) {
9484                mDisplayList.setLeft(left);
9485            }
9486
9487            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9488
9489            if (!matrixIsIdentity) {
9490                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9491                    // A change in dimension means an auto-centered pivot point changes, too
9492                    mTransformationInfo.mMatrixDirty = true;
9493                }
9494                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9495                invalidate(true);
9496            }
9497            mBackgroundSizeChanged = true;
9498            invalidateParentIfNeeded();
9499            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9500                // View was rejected last time it was drawn by its parent; this may have changed
9501                invalidateParentIfNeeded();
9502            }
9503        }
9504    }
9505
9506    /**
9507     * Right position of this view relative to its parent.
9508     *
9509     * @return The right edge of this view, in pixels.
9510     */
9511    @ViewDebug.CapturedViewProperty
9512    public final int getRight() {
9513        return mRight;
9514    }
9515
9516    /**
9517     * Sets the right position of this view relative to its parent. This method is meant to be called
9518     * by the layout system and should not generally be called otherwise, because the property
9519     * may be changed at any time by the layout.
9520     *
9521     * @param right The bottom of this view, in pixels.
9522     */
9523    public final void setRight(int right) {
9524        if (right != mRight) {
9525            updateMatrix();
9526            final boolean matrixIsIdentity = mTransformationInfo == null
9527                    || mTransformationInfo.mMatrixIsIdentity;
9528            if (matrixIsIdentity) {
9529                if (mAttachInfo != null) {
9530                    int maxRight;
9531                    if (right < mRight) {
9532                        maxRight = mRight;
9533                    } else {
9534                        maxRight = right;
9535                    }
9536                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9537                }
9538            } else {
9539                // Double-invalidation is necessary to capture view's old and new areas
9540                invalidate(true);
9541            }
9542
9543            int oldWidth = mRight - mLeft;
9544            int height = mBottom - mTop;
9545
9546            mRight = right;
9547            if (mDisplayList != null) {
9548                mDisplayList.setRight(mRight);
9549            }
9550
9551            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9552
9553            if (!matrixIsIdentity) {
9554                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9555                    // A change in dimension means an auto-centered pivot point changes, too
9556                    mTransformationInfo.mMatrixDirty = true;
9557                }
9558                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9559                invalidate(true);
9560            }
9561            mBackgroundSizeChanged = true;
9562            invalidateParentIfNeeded();
9563            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9564                // View was rejected last time it was drawn by its parent; this may have changed
9565                invalidateParentIfNeeded();
9566            }
9567        }
9568    }
9569
9570    /**
9571     * The visual x position of this view, in pixels. This is equivalent to the
9572     * {@link #setTranslationX(float) translationX} property plus the current
9573     * {@link #getLeft() left} property.
9574     *
9575     * @return The visual x position of this view, in pixels.
9576     */
9577    @ViewDebug.ExportedProperty(category = "drawing")
9578    public float getX() {
9579        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9580    }
9581
9582    /**
9583     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9584     * {@link #setTranslationX(float) translationX} property to be the difference between
9585     * the x value passed in and the current {@link #getLeft() left} property.
9586     *
9587     * @param x The visual x position of this view, in pixels.
9588     */
9589    public void setX(float x) {
9590        setTranslationX(x - mLeft);
9591    }
9592
9593    /**
9594     * The visual y position of this view, in pixels. This is equivalent to the
9595     * {@link #setTranslationY(float) translationY} property plus the current
9596     * {@link #getTop() top} property.
9597     *
9598     * @return The visual y position of this view, in pixels.
9599     */
9600    @ViewDebug.ExportedProperty(category = "drawing")
9601    public float getY() {
9602        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9603    }
9604
9605    /**
9606     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9607     * {@link #setTranslationY(float) translationY} property to be the difference between
9608     * the y value passed in and the current {@link #getTop() top} property.
9609     *
9610     * @param y The visual y position of this view, in pixels.
9611     */
9612    public void setY(float y) {
9613        setTranslationY(y - mTop);
9614    }
9615
9616
9617    /**
9618     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9619     * This position is post-layout, in addition to wherever the object's
9620     * layout placed it.
9621     *
9622     * @return The horizontal position of this view relative to its left position, in pixels.
9623     */
9624    @ViewDebug.ExportedProperty(category = "drawing")
9625    public float getTranslationX() {
9626        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9627    }
9628
9629    /**
9630     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9631     * This effectively positions the object post-layout, in addition to wherever the object's
9632     * layout placed it.
9633     *
9634     * @param translationX The horizontal position of this view relative to its left position,
9635     * in pixels.
9636     *
9637     * @attr ref android.R.styleable#View_translationX
9638     */
9639    public void setTranslationX(float translationX) {
9640        ensureTransformationInfo();
9641        final TransformationInfo info = mTransformationInfo;
9642        if (info.mTranslationX != translationX) {
9643            // Double-invalidation is necessary to capture view's old and new areas
9644            invalidateViewProperty(true, false);
9645            info.mTranslationX = translationX;
9646            info.mMatrixDirty = true;
9647            invalidateViewProperty(false, true);
9648            if (mDisplayList != null) {
9649                mDisplayList.setTranslationX(translationX);
9650            }
9651            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9652                // View was rejected last time it was drawn by its parent; this may have changed
9653                invalidateParentIfNeeded();
9654            }
9655        }
9656    }
9657
9658    /**
9659     * The horizontal location of this view relative to its {@link #getTop() top} position.
9660     * This position is post-layout, in addition to wherever the object's
9661     * layout placed it.
9662     *
9663     * @return The vertical position of this view relative to its top position,
9664     * in pixels.
9665     */
9666    @ViewDebug.ExportedProperty(category = "drawing")
9667    public float getTranslationY() {
9668        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9669    }
9670
9671    /**
9672     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9673     * This effectively positions the object post-layout, in addition to wherever the object's
9674     * layout placed it.
9675     *
9676     * @param translationY The vertical position of this view relative to its top position,
9677     * in pixels.
9678     *
9679     * @attr ref android.R.styleable#View_translationY
9680     */
9681    public void setTranslationY(float translationY) {
9682        ensureTransformationInfo();
9683        final TransformationInfo info = mTransformationInfo;
9684        if (info.mTranslationY != translationY) {
9685            invalidateViewProperty(true, false);
9686            info.mTranslationY = translationY;
9687            info.mMatrixDirty = true;
9688            invalidateViewProperty(false, true);
9689            if (mDisplayList != null) {
9690                mDisplayList.setTranslationY(translationY);
9691            }
9692            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9693                // View was rejected last time it was drawn by its parent; this may have changed
9694                invalidateParentIfNeeded();
9695            }
9696        }
9697    }
9698
9699    /**
9700     * Hit rectangle in parent's coordinates
9701     *
9702     * @param outRect The hit rectangle of the view.
9703     */
9704    public void getHitRect(Rect outRect) {
9705        updateMatrix();
9706        final TransformationInfo info = mTransformationInfo;
9707        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9708            outRect.set(mLeft, mTop, mRight, mBottom);
9709        } else {
9710            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9711            tmpRect.set(-info.mPivotX, -info.mPivotY,
9712                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9713            info.mMatrix.mapRect(tmpRect);
9714            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9715                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9716        }
9717    }
9718
9719    /**
9720     * Determines whether the given point, in local coordinates is inside the view.
9721     */
9722    /*package*/ final boolean pointInView(float localX, float localY) {
9723        return localX >= 0 && localX < (mRight - mLeft)
9724                && localY >= 0 && localY < (mBottom - mTop);
9725    }
9726
9727    /**
9728     * Utility method to determine whether the given point, in local coordinates,
9729     * is inside the view, where the area of the view is expanded by the slop factor.
9730     * This method is called while processing touch-move events to determine if the event
9731     * is still within the view.
9732     */
9733    private boolean pointInView(float localX, float localY, float slop) {
9734        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9735                localY < ((mBottom - mTop) + slop);
9736    }
9737
9738    /**
9739     * When a view has focus and the user navigates away from it, the next view is searched for
9740     * starting from the rectangle filled in by this method.
9741     *
9742     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9743     * of the view.  However, if your view maintains some idea of internal selection,
9744     * such as a cursor, or a selected row or column, you should override this method and
9745     * fill in a more specific rectangle.
9746     *
9747     * @param r The rectangle to fill in, in this view's coordinates.
9748     */
9749    public void getFocusedRect(Rect r) {
9750        getDrawingRect(r);
9751    }
9752
9753    /**
9754     * If some part of this view is not clipped by any of its parents, then
9755     * return that area in r in global (root) coordinates. To convert r to local
9756     * coordinates (without taking possible View rotations into account), offset
9757     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9758     * If the view is completely clipped or translated out, return false.
9759     *
9760     * @param r If true is returned, r holds the global coordinates of the
9761     *        visible portion of this view.
9762     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9763     *        between this view and its root. globalOffet may be null.
9764     * @return true if r is non-empty (i.e. part of the view is visible at the
9765     *         root level.
9766     */
9767    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9768        int width = mRight - mLeft;
9769        int height = mBottom - mTop;
9770        if (width > 0 && height > 0) {
9771            r.set(0, 0, width, height);
9772            if (globalOffset != null) {
9773                globalOffset.set(-mScrollX, -mScrollY);
9774            }
9775            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9776        }
9777        return false;
9778    }
9779
9780    public final boolean getGlobalVisibleRect(Rect r) {
9781        return getGlobalVisibleRect(r, null);
9782    }
9783
9784    public final boolean getLocalVisibleRect(Rect r) {
9785        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9786        if (getGlobalVisibleRect(r, offset)) {
9787            r.offset(-offset.x, -offset.y); // make r local
9788            return true;
9789        }
9790        return false;
9791    }
9792
9793    /**
9794     * Offset this view's vertical location by the specified number of pixels.
9795     *
9796     * @param offset the number of pixels to offset the view by
9797     */
9798    public void offsetTopAndBottom(int offset) {
9799        if (offset != 0) {
9800            updateMatrix();
9801            final boolean matrixIsIdentity = mTransformationInfo == null
9802                    || mTransformationInfo.mMatrixIsIdentity;
9803            if (matrixIsIdentity) {
9804                if (mDisplayList != null) {
9805                    invalidateViewProperty(false, false);
9806                } else {
9807                    final ViewParent p = mParent;
9808                    if (p != null && mAttachInfo != null) {
9809                        final Rect r = mAttachInfo.mTmpInvalRect;
9810                        int minTop;
9811                        int maxBottom;
9812                        int yLoc;
9813                        if (offset < 0) {
9814                            minTop = mTop + offset;
9815                            maxBottom = mBottom;
9816                            yLoc = offset;
9817                        } else {
9818                            minTop = mTop;
9819                            maxBottom = mBottom + offset;
9820                            yLoc = 0;
9821                        }
9822                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9823                        p.invalidateChild(this, r);
9824                    }
9825                }
9826            } else {
9827                invalidateViewProperty(false, false);
9828            }
9829
9830            mTop += offset;
9831            mBottom += offset;
9832            if (mDisplayList != null) {
9833                mDisplayList.offsetTopBottom(offset);
9834                invalidateViewProperty(false, false);
9835            } else {
9836                if (!matrixIsIdentity) {
9837                    invalidateViewProperty(false, true);
9838                }
9839                invalidateParentIfNeeded();
9840            }
9841        }
9842    }
9843
9844    /**
9845     * Offset this view's horizontal location by the specified amount of pixels.
9846     *
9847     * @param offset the numer of pixels to offset the view by
9848     */
9849    public void offsetLeftAndRight(int offset) {
9850        if (offset != 0) {
9851            updateMatrix();
9852            final boolean matrixIsIdentity = mTransformationInfo == null
9853                    || mTransformationInfo.mMatrixIsIdentity;
9854            if (matrixIsIdentity) {
9855                if (mDisplayList != null) {
9856                    invalidateViewProperty(false, false);
9857                } else {
9858                    final ViewParent p = mParent;
9859                    if (p != null && mAttachInfo != null) {
9860                        final Rect r = mAttachInfo.mTmpInvalRect;
9861                        int minLeft;
9862                        int maxRight;
9863                        if (offset < 0) {
9864                            minLeft = mLeft + offset;
9865                            maxRight = mRight;
9866                        } else {
9867                            minLeft = mLeft;
9868                            maxRight = mRight + offset;
9869                        }
9870                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9871                        p.invalidateChild(this, r);
9872                    }
9873                }
9874            } else {
9875                invalidateViewProperty(false, false);
9876            }
9877
9878            mLeft += offset;
9879            mRight += offset;
9880            if (mDisplayList != null) {
9881                mDisplayList.offsetLeftRight(offset);
9882                invalidateViewProperty(false, false);
9883            } else {
9884                if (!matrixIsIdentity) {
9885                    invalidateViewProperty(false, true);
9886                }
9887                invalidateParentIfNeeded();
9888            }
9889        }
9890    }
9891
9892    /**
9893     * Get the LayoutParams associated with this view. All views should have
9894     * layout parameters. These supply parameters to the <i>parent</i> of this
9895     * view specifying how it should be arranged. There are many subclasses of
9896     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9897     * of ViewGroup that are responsible for arranging their children.
9898     *
9899     * This method may return null if this View is not attached to a parent
9900     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9901     * was not invoked successfully. When a View is attached to a parent
9902     * ViewGroup, this method must not return null.
9903     *
9904     * @return The LayoutParams associated with this view, or null if no
9905     *         parameters have been set yet
9906     */
9907    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9908    public ViewGroup.LayoutParams getLayoutParams() {
9909        return mLayoutParams;
9910    }
9911
9912    /**
9913     * Set the layout parameters associated with this view. These supply
9914     * parameters to the <i>parent</i> of this view specifying how it should be
9915     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9916     * correspond to the different subclasses of ViewGroup that are responsible
9917     * for arranging their children.
9918     *
9919     * @param params The layout parameters for this view, cannot be null
9920     */
9921    public void setLayoutParams(ViewGroup.LayoutParams params) {
9922        if (params == null) {
9923            throw new NullPointerException("Layout parameters cannot be null");
9924        }
9925        mLayoutParams = params;
9926        if (mParent instanceof ViewGroup) {
9927            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9928        }
9929        requestLayout();
9930    }
9931
9932    /**
9933     * Set the scrolled position of your view. This will cause a call to
9934     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9935     * invalidated.
9936     * @param x the x position to scroll to
9937     * @param y the y position to scroll to
9938     */
9939    public void scrollTo(int x, int y) {
9940        if (mScrollX != x || mScrollY != y) {
9941            int oldX = mScrollX;
9942            int oldY = mScrollY;
9943            mScrollX = x;
9944            mScrollY = y;
9945            invalidateParentCaches();
9946            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9947            if (!awakenScrollBars()) {
9948                postInvalidateOnAnimation();
9949            }
9950        }
9951    }
9952
9953    /**
9954     * Move the scrolled position of your view. This will cause a call to
9955     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9956     * invalidated.
9957     * @param x the amount of pixels to scroll by horizontally
9958     * @param y the amount of pixels to scroll by vertically
9959     */
9960    public void scrollBy(int x, int y) {
9961        scrollTo(mScrollX + x, mScrollY + y);
9962    }
9963
9964    /**
9965     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9966     * animation to fade the scrollbars out after a default delay. If a subclass
9967     * provides animated scrolling, the start delay should equal the duration
9968     * of the scrolling animation.</p>
9969     *
9970     * <p>The animation starts only if at least one of the scrollbars is
9971     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9972     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9973     * this method returns true, and false otherwise. If the animation is
9974     * started, this method calls {@link #invalidate()}; in that case the
9975     * caller should not call {@link #invalidate()}.</p>
9976     *
9977     * <p>This method should be invoked every time a subclass directly updates
9978     * the scroll parameters.</p>
9979     *
9980     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9981     * and {@link #scrollTo(int, int)}.</p>
9982     *
9983     * @return true if the animation is played, false otherwise
9984     *
9985     * @see #awakenScrollBars(int)
9986     * @see #scrollBy(int, int)
9987     * @see #scrollTo(int, int)
9988     * @see #isHorizontalScrollBarEnabled()
9989     * @see #isVerticalScrollBarEnabled()
9990     * @see #setHorizontalScrollBarEnabled(boolean)
9991     * @see #setVerticalScrollBarEnabled(boolean)
9992     */
9993    protected boolean awakenScrollBars() {
9994        return mScrollCache != null &&
9995                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9996    }
9997
9998    /**
9999     * Trigger the scrollbars to draw.
10000     * This method differs from awakenScrollBars() only in its default duration.
10001     * initialAwakenScrollBars() will show the scroll bars for longer than
10002     * usual to give the user more of a chance to notice them.
10003     *
10004     * @return true if the animation is played, false otherwise.
10005     */
10006    private boolean initialAwakenScrollBars() {
10007        return mScrollCache != null &&
10008                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10009    }
10010
10011    /**
10012     * <p>
10013     * Trigger the scrollbars to draw. When invoked this method starts an
10014     * animation to fade the scrollbars out after a fixed delay. If a subclass
10015     * provides animated scrolling, the start delay should equal the duration of
10016     * the scrolling animation.
10017     * </p>
10018     *
10019     * <p>
10020     * The animation starts only if at least one of the scrollbars is enabled,
10021     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10022     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10023     * this method returns true, and false otherwise. If the animation is
10024     * started, this method calls {@link #invalidate()}; in that case the caller
10025     * should not call {@link #invalidate()}.
10026     * </p>
10027     *
10028     * <p>
10029     * This method should be invoked everytime a subclass directly updates the
10030     * scroll parameters.
10031     * </p>
10032     *
10033     * @param startDelay the delay, in milliseconds, after which the animation
10034     *        should start; when the delay is 0, the animation starts
10035     *        immediately
10036     * @return true if the animation is played, false otherwise
10037     *
10038     * @see #scrollBy(int, int)
10039     * @see #scrollTo(int, int)
10040     * @see #isHorizontalScrollBarEnabled()
10041     * @see #isVerticalScrollBarEnabled()
10042     * @see #setHorizontalScrollBarEnabled(boolean)
10043     * @see #setVerticalScrollBarEnabled(boolean)
10044     */
10045    protected boolean awakenScrollBars(int startDelay) {
10046        return awakenScrollBars(startDelay, true);
10047    }
10048
10049    /**
10050     * <p>
10051     * Trigger the scrollbars to draw. When invoked this method starts an
10052     * animation to fade the scrollbars out after a fixed delay. If a subclass
10053     * provides animated scrolling, the start delay should equal the duration of
10054     * the scrolling animation.
10055     * </p>
10056     *
10057     * <p>
10058     * The animation starts only if at least one of the scrollbars is enabled,
10059     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10060     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10061     * this method returns true, and false otherwise. If the animation is
10062     * started, this method calls {@link #invalidate()} if the invalidate parameter
10063     * is set to true; in that case the caller
10064     * should not call {@link #invalidate()}.
10065     * </p>
10066     *
10067     * <p>
10068     * This method should be invoked everytime a subclass directly updates the
10069     * scroll parameters.
10070     * </p>
10071     *
10072     * @param startDelay the delay, in milliseconds, after which the animation
10073     *        should start; when the delay is 0, the animation starts
10074     *        immediately
10075     *
10076     * @param invalidate Wheter this method should call invalidate
10077     *
10078     * @return true if the animation is played, false otherwise
10079     *
10080     * @see #scrollBy(int, int)
10081     * @see #scrollTo(int, int)
10082     * @see #isHorizontalScrollBarEnabled()
10083     * @see #isVerticalScrollBarEnabled()
10084     * @see #setHorizontalScrollBarEnabled(boolean)
10085     * @see #setVerticalScrollBarEnabled(boolean)
10086     */
10087    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10088        final ScrollabilityCache scrollCache = mScrollCache;
10089
10090        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10091            return false;
10092        }
10093
10094        if (scrollCache.scrollBar == null) {
10095            scrollCache.scrollBar = new ScrollBarDrawable();
10096        }
10097
10098        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10099
10100            if (invalidate) {
10101                // Invalidate to show the scrollbars
10102                postInvalidateOnAnimation();
10103            }
10104
10105            if (scrollCache.state == ScrollabilityCache.OFF) {
10106                // FIXME: this is copied from WindowManagerService.
10107                // We should get this value from the system when it
10108                // is possible to do so.
10109                final int KEY_REPEAT_FIRST_DELAY = 750;
10110                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10111            }
10112
10113            // Tell mScrollCache when we should start fading. This may
10114            // extend the fade start time if one was already scheduled
10115            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10116            scrollCache.fadeStartTime = fadeStartTime;
10117            scrollCache.state = ScrollabilityCache.ON;
10118
10119            // Schedule our fader to run, unscheduling any old ones first
10120            if (mAttachInfo != null) {
10121                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10122                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10123            }
10124
10125            return true;
10126        }
10127
10128        return false;
10129    }
10130
10131    /**
10132     * Do not invalidate views which are not visible and which are not running an animation. They
10133     * will not get drawn and they should not set dirty flags as if they will be drawn
10134     */
10135    private boolean skipInvalidate() {
10136        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10137                (!(mParent instanceof ViewGroup) ||
10138                        !((ViewGroup) mParent).isViewTransitioning(this));
10139    }
10140    /**
10141     * Mark the area defined by dirty as needing to be drawn. If the view is
10142     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10143     * in the future. This must be called from a UI thread. To call from a non-UI
10144     * thread, call {@link #postInvalidate()}.
10145     *
10146     * WARNING: This method is destructive to dirty.
10147     * @param dirty the rectangle representing the bounds of the dirty region
10148     */
10149    public void invalidate(Rect dirty) {
10150        if (skipInvalidate()) {
10151            return;
10152        }
10153        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10154                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
10155                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
10156            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10157            mPrivateFlags |= INVALIDATED;
10158            mPrivateFlags |= DIRTY;
10159            final ViewParent p = mParent;
10160            final AttachInfo ai = mAttachInfo;
10161            //noinspection PointlessBooleanExpression,ConstantConditions
10162            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10163                if (p != null && ai != null && ai.mHardwareAccelerated) {
10164                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10165                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10166                    p.invalidateChild(this, null);
10167                    return;
10168                }
10169            }
10170            if (p != null && ai != null) {
10171                final int scrollX = mScrollX;
10172                final int scrollY = mScrollY;
10173                final Rect r = ai.mTmpInvalRect;
10174                r.set(dirty.left - scrollX, dirty.top - scrollY,
10175                        dirty.right - scrollX, dirty.bottom - scrollY);
10176                mParent.invalidateChild(this, r);
10177            }
10178        }
10179    }
10180
10181    /**
10182     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10183     * The coordinates of the dirty rect are relative to the view.
10184     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10185     * will be called at some point in the future. This must be called from
10186     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10187     * @param l the left position of the dirty region
10188     * @param t the top position of the dirty region
10189     * @param r the right position of the dirty region
10190     * @param b the bottom position of the dirty region
10191     */
10192    public void invalidate(int l, int t, int r, int b) {
10193        if (skipInvalidate()) {
10194            return;
10195        }
10196        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10197                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
10198                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
10199            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10200            mPrivateFlags |= INVALIDATED;
10201            mPrivateFlags |= DIRTY;
10202            final ViewParent p = mParent;
10203            final AttachInfo ai = mAttachInfo;
10204            //noinspection PointlessBooleanExpression,ConstantConditions
10205            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10206                if (p != null && ai != null && ai.mHardwareAccelerated) {
10207                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10208                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10209                    p.invalidateChild(this, null);
10210                    return;
10211                }
10212            }
10213            if (p != null && ai != null && l < r && t < b) {
10214                final int scrollX = mScrollX;
10215                final int scrollY = mScrollY;
10216                final Rect tmpr = ai.mTmpInvalRect;
10217                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10218                p.invalidateChild(this, tmpr);
10219            }
10220        }
10221    }
10222
10223    /**
10224     * Invalidate the whole view. If the view is visible,
10225     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10226     * the future. This must be called from a UI thread. To call from a non-UI thread,
10227     * call {@link #postInvalidate()}.
10228     */
10229    public void invalidate() {
10230        invalidate(true);
10231    }
10232
10233    /**
10234     * This is where the invalidate() work actually happens. A full invalidate()
10235     * causes the drawing cache to be invalidated, but this function can be called with
10236     * invalidateCache set to false to skip that invalidation step for cases that do not
10237     * need it (for example, a component that remains at the same dimensions with the same
10238     * content).
10239     *
10240     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10241     * well. This is usually true for a full invalidate, but may be set to false if the
10242     * View's contents or dimensions have not changed.
10243     */
10244    void invalidate(boolean invalidateCache) {
10245        if (skipInvalidate()) {
10246            return;
10247        }
10248        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
10249                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
10250                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
10251            mLastIsOpaque = isOpaque();
10252            mPrivateFlags &= ~DRAWN;
10253            mPrivateFlags |= DIRTY;
10254            if (invalidateCache) {
10255                mPrivateFlags |= INVALIDATED;
10256                mPrivateFlags &= ~DRAWING_CACHE_VALID;
10257            }
10258            final AttachInfo ai = mAttachInfo;
10259            final ViewParent p = mParent;
10260            //noinspection PointlessBooleanExpression,ConstantConditions
10261            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10262                if (p != null && ai != null && ai.mHardwareAccelerated) {
10263                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10264                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10265                    p.invalidateChild(this, null);
10266                    return;
10267                }
10268            }
10269
10270            if (p != null && ai != null) {
10271                final Rect r = ai.mTmpInvalRect;
10272                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10273                // Don't call invalidate -- we don't want to internally scroll
10274                // our own bounds
10275                p.invalidateChild(this, r);
10276            }
10277        }
10278    }
10279
10280    /**
10281     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10282     * set any flags or handle all of the cases handled by the default invalidation methods.
10283     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10284     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10285     * walk up the hierarchy, transforming the dirty rect as necessary.
10286     *
10287     * The method also handles normal invalidation logic if display list properties are not
10288     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10289     * backup approach, to handle these cases used in the various property-setting methods.
10290     *
10291     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10292     * are not being used in this view
10293     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10294     * list properties are not being used in this view
10295     */
10296    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10297        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10298            if (invalidateParent) {
10299                invalidateParentCaches();
10300            }
10301            if (forceRedraw) {
10302                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10303            }
10304            invalidate(false);
10305        } else {
10306            final AttachInfo ai = mAttachInfo;
10307            final ViewParent p = mParent;
10308            if (p != null && ai != null) {
10309                final Rect r = ai.mTmpInvalRect;
10310                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10311                if (mParent instanceof ViewGroup) {
10312                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10313                } else {
10314                    mParent.invalidateChild(this, r);
10315                }
10316            }
10317        }
10318    }
10319
10320    /**
10321     * Utility method to transform a given Rect by the current matrix of this view.
10322     */
10323    void transformRect(final Rect rect) {
10324        if (!getMatrix().isIdentity()) {
10325            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10326            boundingRect.set(rect);
10327            getMatrix().mapRect(boundingRect);
10328            rect.set((int) (boundingRect.left - 0.5f),
10329                    (int) (boundingRect.top - 0.5f),
10330                    (int) (boundingRect.right + 0.5f),
10331                    (int) (boundingRect.bottom + 0.5f));
10332        }
10333    }
10334
10335    /**
10336     * Used to indicate that the parent of this view should clear its caches. This functionality
10337     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10338     * which is necessary when various parent-managed properties of the view change, such as
10339     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10340     * clears the parent caches and does not causes an invalidate event.
10341     *
10342     * @hide
10343     */
10344    protected void invalidateParentCaches() {
10345        if (mParent instanceof View) {
10346            ((View) mParent).mPrivateFlags |= INVALIDATED;
10347        }
10348    }
10349
10350    /**
10351     * Used to indicate that the parent of this view should be invalidated. This functionality
10352     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10353     * which is necessary when various parent-managed properties of the view change, such as
10354     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10355     * an invalidation event to the parent.
10356     *
10357     * @hide
10358     */
10359    protected void invalidateParentIfNeeded() {
10360        if (isHardwareAccelerated() && mParent instanceof View) {
10361            ((View) mParent).invalidate(true);
10362        }
10363    }
10364
10365    /**
10366     * Indicates whether this View is opaque. An opaque View guarantees that it will
10367     * draw all the pixels overlapping its bounds using a fully opaque color.
10368     *
10369     * Subclasses of View should override this method whenever possible to indicate
10370     * whether an instance is opaque. Opaque Views are treated in a special way by
10371     * the View hierarchy, possibly allowing it to perform optimizations during
10372     * invalidate/draw passes.
10373     *
10374     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10375     */
10376    @ViewDebug.ExportedProperty(category = "drawing")
10377    public boolean isOpaque() {
10378        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10379                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
10380                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
10381    }
10382
10383    /**
10384     * @hide
10385     */
10386    protected void computeOpaqueFlags() {
10387        // Opaque if:
10388        //   - Has a background
10389        //   - Background is opaque
10390        //   - Doesn't have scrollbars or scrollbars are inside overlay
10391
10392        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10393            mPrivateFlags |= OPAQUE_BACKGROUND;
10394        } else {
10395            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10396        }
10397
10398        final int flags = mViewFlags;
10399        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10400                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10401            mPrivateFlags |= OPAQUE_SCROLLBARS;
10402        } else {
10403            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10404        }
10405    }
10406
10407    /**
10408     * @hide
10409     */
10410    protected boolean hasOpaqueScrollbars() {
10411        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10412    }
10413
10414    /**
10415     * @return A handler associated with the thread running the View. This
10416     * handler can be used to pump events in the UI events queue.
10417     */
10418    public Handler getHandler() {
10419        if (mAttachInfo != null) {
10420            return mAttachInfo.mHandler;
10421        }
10422        return null;
10423    }
10424
10425    /**
10426     * Gets the view root associated with the View.
10427     * @return The view root, or null if none.
10428     * @hide
10429     */
10430    public ViewRootImpl getViewRootImpl() {
10431        if (mAttachInfo != null) {
10432            return mAttachInfo.mViewRootImpl;
10433        }
10434        return null;
10435    }
10436
10437    /**
10438     * <p>Causes the Runnable to be added to the message queue.
10439     * The runnable will be run on the user interface thread.</p>
10440     *
10441     * <p>This method can be invoked from outside of the UI thread
10442     * only when this View is attached to a window.</p>
10443     *
10444     * @param action The Runnable that will be executed.
10445     *
10446     * @return Returns true if the Runnable was successfully placed in to the
10447     *         message queue.  Returns false on failure, usually because the
10448     *         looper processing the message queue is exiting.
10449     *
10450     * @see #postDelayed
10451     * @see #removeCallbacks
10452     */
10453    public boolean post(Runnable action) {
10454        final AttachInfo attachInfo = mAttachInfo;
10455        if (attachInfo != null) {
10456            return attachInfo.mHandler.post(action);
10457        }
10458        // Assume that post will succeed later
10459        ViewRootImpl.getRunQueue().post(action);
10460        return true;
10461    }
10462
10463    /**
10464     * <p>Causes the Runnable to be added to the message queue, to be run
10465     * after the specified amount of time elapses.
10466     * The runnable will be run on the user interface thread.</p>
10467     *
10468     * <p>This method can be invoked from outside of the UI thread
10469     * only when this View is attached to a window.</p>
10470     *
10471     * @param action The Runnable that will be executed.
10472     * @param delayMillis The delay (in milliseconds) until the Runnable
10473     *        will be executed.
10474     *
10475     * @return true if the Runnable was successfully placed in to the
10476     *         message queue.  Returns false on failure, usually because the
10477     *         looper processing the message queue is exiting.  Note that a
10478     *         result of true does not mean the Runnable will be processed --
10479     *         if the looper is quit before the delivery time of the message
10480     *         occurs then the message will be dropped.
10481     *
10482     * @see #post
10483     * @see #removeCallbacks
10484     */
10485    public boolean postDelayed(Runnable action, long delayMillis) {
10486        final AttachInfo attachInfo = mAttachInfo;
10487        if (attachInfo != null) {
10488            return attachInfo.mHandler.postDelayed(action, delayMillis);
10489        }
10490        // Assume that post will succeed later
10491        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10492        return true;
10493    }
10494
10495    /**
10496     * <p>Causes the Runnable to execute on the next animation time step.
10497     * The runnable will be run on the user interface thread.</p>
10498     *
10499     * <p>This method can be invoked from outside of the UI thread
10500     * only when this View is attached to a window.</p>
10501     *
10502     * @param action The Runnable that will be executed.
10503     *
10504     * @see #postOnAnimationDelayed
10505     * @see #removeCallbacks
10506     */
10507    public void postOnAnimation(Runnable action) {
10508        final AttachInfo attachInfo = mAttachInfo;
10509        if (attachInfo != null) {
10510            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10511                    Choreographer.CALLBACK_ANIMATION, action, null);
10512        } else {
10513            // Assume that post will succeed later
10514            ViewRootImpl.getRunQueue().post(action);
10515        }
10516    }
10517
10518    /**
10519     * <p>Causes the Runnable to execute on the next animation time step,
10520     * after the specified amount of time elapses.
10521     * The runnable will be run on the user interface thread.</p>
10522     *
10523     * <p>This method can be invoked from outside of the UI thread
10524     * only when this View is attached to a window.</p>
10525     *
10526     * @param action The Runnable that will be executed.
10527     * @param delayMillis The delay (in milliseconds) until the Runnable
10528     *        will be executed.
10529     *
10530     * @see #postOnAnimation
10531     * @see #removeCallbacks
10532     */
10533    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10534        final AttachInfo attachInfo = mAttachInfo;
10535        if (attachInfo != null) {
10536            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10537                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10538        } else {
10539            // Assume that post will succeed later
10540            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10541        }
10542    }
10543
10544    /**
10545     * <p>Removes the specified Runnable from the message queue.</p>
10546     *
10547     * <p>This method can be invoked from outside of the UI thread
10548     * only when this View is attached to a window.</p>
10549     *
10550     * @param action The Runnable to remove from the message handling queue
10551     *
10552     * @return true if this view could ask the Handler to remove the Runnable,
10553     *         false otherwise. When the returned value is true, the Runnable
10554     *         may or may not have been actually removed from the message queue
10555     *         (for instance, if the Runnable was not in the queue already.)
10556     *
10557     * @see #post
10558     * @see #postDelayed
10559     * @see #postOnAnimation
10560     * @see #postOnAnimationDelayed
10561     */
10562    public boolean removeCallbacks(Runnable action) {
10563        if (action != null) {
10564            final AttachInfo attachInfo = mAttachInfo;
10565            if (attachInfo != null) {
10566                attachInfo.mHandler.removeCallbacks(action);
10567                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10568                        Choreographer.CALLBACK_ANIMATION, action, null);
10569            } else {
10570                // Assume that post will succeed later
10571                ViewRootImpl.getRunQueue().removeCallbacks(action);
10572            }
10573        }
10574        return true;
10575    }
10576
10577    /**
10578     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10579     * Use this to invalidate the View from a non-UI thread.</p>
10580     *
10581     * <p>This method can be invoked from outside of the UI thread
10582     * only when this View is attached to a window.</p>
10583     *
10584     * @see #invalidate()
10585     * @see #postInvalidateDelayed(long)
10586     */
10587    public void postInvalidate() {
10588        postInvalidateDelayed(0);
10589    }
10590
10591    /**
10592     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10593     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10594     *
10595     * <p>This method can be invoked from outside of the UI thread
10596     * only when this View is attached to a window.</p>
10597     *
10598     * @param left The left coordinate of the rectangle to invalidate.
10599     * @param top The top coordinate of the rectangle to invalidate.
10600     * @param right The right coordinate of the rectangle to invalidate.
10601     * @param bottom The bottom coordinate of the rectangle to invalidate.
10602     *
10603     * @see #invalidate(int, int, int, int)
10604     * @see #invalidate(Rect)
10605     * @see #postInvalidateDelayed(long, int, int, int, int)
10606     */
10607    public void postInvalidate(int left, int top, int right, int bottom) {
10608        postInvalidateDelayed(0, left, top, right, bottom);
10609    }
10610
10611    /**
10612     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10613     * loop. Waits for the specified amount of time.</p>
10614     *
10615     * <p>This method can be invoked from outside of the UI thread
10616     * only when this View is attached to a window.</p>
10617     *
10618     * @param delayMilliseconds the duration in milliseconds to delay the
10619     *         invalidation by
10620     *
10621     * @see #invalidate()
10622     * @see #postInvalidate()
10623     */
10624    public void postInvalidateDelayed(long delayMilliseconds) {
10625        // We try only with the AttachInfo because there's no point in invalidating
10626        // if we are not attached to our window
10627        final AttachInfo attachInfo = mAttachInfo;
10628        if (attachInfo != null) {
10629            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10630        }
10631    }
10632
10633    /**
10634     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10635     * through the event loop. Waits for the specified amount of time.</p>
10636     *
10637     * <p>This method can be invoked from outside of the UI thread
10638     * only when this View is attached to a window.</p>
10639     *
10640     * @param delayMilliseconds the duration in milliseconds to delay the
10641     *         invalidation by
10642     * @param left The left coordinate of the rectangle to invalidate.
10643     * @param top The top coordinate of the rectangle to invalidate.
10644     * @param right The right coordinate of the rectangle to invalidate.
10645     * @param bottom The bottom coordinate of the rectangle to invalidate.
10646     *
10647     * @see #invalidate(int, int, int, int)
10648     * @see #invalidate(Rect)
10649     * @see #postInvalidate(int, int, int, int)
10650     */
10651    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10652            int right, int bottom) {
10653
10654        // We try only with the AttachInfo because there's no point in invalidating
10655        // if we are not attached to our window
10656        final AttachInfo attachInfo = mAttachInfo;
10657        if (attachInfo != null) {
10658            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10659            info.target = this;
10660            info.left = left;
10661            info.top = top;
10662            info.right = right;
10663            info.bottom = bottom;
10664
10665            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10666        }
10667    }
10668
10669    /**
10670     * <p>Cause an invalidate to happen on the next animation time step, typically the
10671     * next display frame.</p>
10672     *
10673     * <p>This method can be invoked from outside of the UI thread
10674     * only when this View is attached to a window.</p>
10675     *
10676     * @see #invalidate()
10677     */
10678    public void postInvalidateOnAnimation() {
10679        // We try only with the AttachInfo because there's no point in invalidating
10680        // if we are not attached to our window
10681        final AttachInfo attachInfo = mAttachInfo;
10682        if (attachInfo != null) {
10683            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10684        }
10685    }
10686
10687    /**
10688     * <p>Cause an invalidate of the specified area to happen on the next animation
10689     * time step, typically the next display frame.</p>
10690     *
10691     * <p>This method can be invoked from outside of the UI thread
10692     * only when this View is attached to a window.</p>
10693     *
10694     * @param left The left coordinate of the rectangle to invalidate.
10695     * @param top The top coordinate of the rectangle to invalidate.
10696     * @param right The right coordinate of the rectangle to invalidate.
10697     * @param bottom The bottom coordinate of the rectangle to invalidate.
10698     *
10699     * @see #invalidate(int, int, int, int)
10700     * @see #invalidate(Rect)
10701     */
10702    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10703        // We try only with the AttachInfo because there's no point in invalidating
10704        // if we are not attached to our window
10705        final AttachInfo attachInfo = mAttachInfo;
10706        if (attachInfo != null) {
10707            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10708            info.target = this;
10709            info.left = left;
10710            info.top = top;
10711            info.right = right;
10712            info.bottom = bottom;
10713
10714            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10715        }
10716    }
10717
10718    /**
10719     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10720     * This event is sent at most once every
10721     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10722     */
10723    private void postSendViewScrolledAccessibilityEventCallback() {
10724        if (mSendViewScrolledAccessibilityEvent == null) {
10725            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10726        }
10727        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10728            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10729            postDelayed(mSendViewScrolledAccessibilityEvent,
10730                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10731        }
10732    }
10733
10734    /**
10735     * Called by a parent to request that a child update its values for mScrollX
10736     * and mScrollY if necessary. This will typically be done if the child is
10737     * animating a scroll using a {@link android.widget.Scroller Scroller}
10738     * object.
10739     */
10740    public void computeScroll() {
10741    }
10742
10743    /**
10744     * <p>Indicate whether the horizontal edges are faded when the view is
10745     * scrolled horizontally.</p>
10746     *
10747     * @return true if the horizontal edges should are faded on scroll, false
10748     *         otherwise
10749     *
10750     * @see #setHorizontalFadingEdgeEnabled(boolean)
10751     *
10752     * @attr ref android.R.styleable#View_requiresFadingEdge
10753     */
10754    public boolean isHorizontalFadingEdgeEnabled() {
10755        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10756    }
10757
10758    /**
10759     * <p>Define whether the horizontal edges should be faded when this view
10760     * is scrolled horizontally.</p>
10761     *
10762     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10763     *                                    be faded when the view is scrolled
10764     *                                    horizontally
10765     *
10766     * @see #isHorizontalFadingEdgeEnabled()
10767     *
10768     * @attr ref android.R.styleable#View_requiresFadingEdge
10769     */
10770    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10771        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10772            if (horizontalFadingEdgeEnabled) {
10773                initScrollCache();
10774            }
10775
10776            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10777        }
10778    }
10779
10780    /**
10781     * <p>Indicate whether the vertical edges are faded when the view is
10782     * scrolled horizontally.</p>
10783     *
10784     * @return true if the vertical edges should are faded on scroll, false
10785     *         otherwise
10786     *
10787     * @see #setVerticalFadingEdgeEnabled(boolean)
10788     *
10789     * @attr ref android.R.styleable#View_requiresFadingEdge
10790     */
10791    public boolean isVerticalFadingEdgeEnabled() {
10792        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10793    }
10794
10795    /**
10796     * <p>Define whether the vertical edges should be faded when this view
10797     * is scrolled vertically.</p>
10798     *
10799     * @param verticalFadingEdgeEnabled true if the vertical edges should
10800     *                                  be faded when the view is scrolled
10801     *                                  vertically
10802     *
10803     * @see #isVerticalFadingEdgeEnabled()
10804     *
10805     * @attr ref android.R.styleable#View_requiresFadingEdge
10806     */
10807    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10808        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10809            if (verticalFadingEdgeEnabled) {
10810                initScrollCache();
10811            }
10812
10813            mViewFlags ^= FADING_EDGE_VERTICAL;
10814        }
10815    }
10816
10817    /**
10818     * Returns the strength, or intensity, of the top faded edge. The strength is
10819     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10820     * returns 0.0 or 1.0 but no value in between.
10821     *
10822     * Subclasses should override this method to provide a smoother fade transition
10823     * when scrolling occurs.
10824     *
10825     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10826     */
10827    protected float getTopFadingEdgeStrength() {
10828        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10829    }
10830
10831    /**
10832     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10833     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10834     * returns 0.0 or 1.0 but no value in between.
10835     *
10836     * Subclasses should override this method to provide a smoother fade transition
10837     * when scrolling occurs.
10838     *
10839     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10840     */
10841    protected float getBottomFadingEdgeStrength() {
10842        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10843                computeVerticalScrollRange() ? 1.0f : 0.0f;
10844    }
10845
10846    /**
10847     * Returns the strength, or intensity, of the left faded edge. The strength is
10848     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10849     * returns 0.0 or 1.0 but no value in between.
10850     *
10851     * Subclasses should override this method to provide a smoother fade transition
10852     * when scrolling occurs.
10853     *
10854     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10855     */
10856    protected float getLeftFadingEdgeStrength() {
10857        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10858    }
10859
10860    /**
10861     * Returns the strength, or intensity, of the right faded edge. The strength is
10862     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10863     * returns 0.0 or 1.0 but no value in between.
10864     *
10865     * Subclasses should override this method to provide a smoother fade transition
10866     * when scrolling occurs.
10867     *
10868     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10869     */
10870    protected float getRightFadingEdgeStrength() {
10871        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10872                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10873    }
10874
10875    /**
10876     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10877     * scrollbar is not drawn by default.</p>
10878     *
10879     * @return true if the horizontal scrollbar should be painted, false
10880     *         otherwise
10881     *
10882     * @see #setHorizontalScrollBarEnabled(boolean)
10883     */
10884    public boolean isHorizontalScrollBarEnabled() {
10885        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10886    }
10887
10888    /**
10889     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10890     * scrollbar is not drawn by default.</p>
10891     *
10892     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10893     *                                   be painted
10894     *
10895     * @see #isHorizontalScrollBarEnabled()
10896     */
10897    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10898        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10899            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10900            computeOpaqueFlags();
10901            resolvePadding();
10902        }
10903    }
10904
10905    /**
10906     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10907     * scrollbar is not drawn by default.</p>
10908     *
10909     * @return true if the vertical scrollbar should be painted, false
10910     *         otherwise
10911     *
10912     * @see #setVerticalScrollBarEnabled(boolean)
10913     */
10914    public boolean isVerticalScrollBarEnabled() {
10915        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10916    }
10917
10918    /**
10919     * <p>Define whether the vertical scrollbar should be drawn or not. The
10920     * scrollbar is not drawn by default.</p>
10921     *
10922     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10923     *                                 be painted
10924     *
10925     * @see #isVerticalScrollBarEnabled()
10926     */
10927    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10928        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10929            mViewFlags ^= SCROLLBARS_VERTICAL;
10930            computeOpaqueFlags();
10931            resolvePadding();
10932        }
10933    }
10934
10935    /**
10936     * @hide
10937     */
10938    protected void recomputePadding() {
10939        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10940    }
10941
10942    /**
10943     * Define whether scrollbars will fade when the view is not scrolling.
10944     *
10945     * @param fadeScrollbars wheter to enable fading
10946     *
10947     * @attr ref android.R.styleable#View_fadeScrollbars
10948     */
10949    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10950        initScrollCache();
10951        final ScrollabilityCache scrollabilityCache = mScrollCache;
10952        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10953        if (fadeScrollbars) {
10954            scrollabilityCache.state = ScrollabilityCache.OFF;
10955        } else {
10956            scrollabilityCache.state = ScrollabilityCache.ON;
10957        }
10958    }
10959
10960    /**
10961     *
10962     * Returns true if scrollbars will fade when this view is not scrolling
10963     *
10964     * @return true if scrollbar fading is enabled
10965     *
10966     * @attr ref android.R.styleable#View_fadeScrollbars
10967     */
10968    public boolean isScrollbarFadingEnabled() {
10969        return mScrollCache != null && mScrollCache.fadeScrollBars;
10970    }
10971
10972    /**
10973     *
10974     * Returns the delay before scrollbars fade.
10975     *
10976     * @return the delay before scrollbars fade
10977     *
10978     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10979     */
10980    public int getScrollBarDefaultDelayBeforeFade() {
10981        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10982                mScrollCache.scrollBarDefaultDelayBeforeFade;
10983    }
10984
10985    /**
10986     * Define the delay before scrollbars fade.
10987     *
10988     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10989     *
10990     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10991     */
10992    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10993        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10994    }
10995
10996    /**
10997     *
10998     * Returns the scrollbar fade duration.
10999     *
11000     * @return the scrollbar fade duration
11001     *
11002     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11003     */
11004    public int getScrollBarFadeDuration() {
11005        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11006                mScrollCache.scrollBarFadeDuration;
11007    }
11008
11009    /**
11010     * Define the scrollbar fade duration.
11011     *
11012     * @param scrollBarFadeDuration - the scrollbar fade duration
11013     *
11014     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11015     */
11016    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11017        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11018    }
11019
11020    /**
11021     *
11022     * Returns the scrollbar size.
11023     *
11024     * @return the scrollbar size
11025     *
11026     * @attr ref android.R.styleable#View_scrollbarSize
11027     */
11028    public int getScrollBarSize() {
11029        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11030                mScrollCache.scrollBarSize;
11031    }
11032
11033    /**
11034     * Define the scrollbar size.
11035     *
11036     * @param scrollBarSize - the scrollbar size
11037     *
11038     * @attr ref android.R.styleable#View_scrollbarSize
11039     */
11040    public void setScrollBarSize(int scrollBarSize) {
11041        getScrollCache().scrollBarSize = scrollBarSize;
11042    }
11043
11044    /**
11045     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11046     * inset. When inset, they add to the padding of the view. And the scrollbars
11047     * can be drawn inside the padding area or on the edge of the view. For example,
11048     * if a view has a background drawable and you want to draw the scrollbars
11049     * inside the padding specified by the drawable, you can use
11050     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11051     * appear at the edge of the view, ignoring the padding, then you can use
11052     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11053     * @param style the style of the scrollbars. Should be one of
11054     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11055     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11056     * @see #SCROLLBARS_INSIDE_OVERLAY
11057     * @see #SCROLLBARS_INSIDE_INSET
11058     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11059     * @see #SCROLLBARS_OUTSIDE_INSET
11060     *
11061     * @attr ref android.R.styleable#View_scrollbarStyle
11062     */
11063    public void setScrollBarStyle(int style) {
11064        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11065            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11066            computeOpaqueFlags();
11067            resolvePadding();
11068        }
11069    }
11070
11071    /**
11072     * <p>Returns the current scrollbar style.</p>
11073     * @return the current scrollbar style
11074     * @see #SCROLLBARS_INSIDE_OVERLAY
11075     * @see #SCROLLBARS_INSIDE_INSET
11076     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11077     * @see #SCROLLBARS_OUTSIDE_INSET
11078     *
11079     * @attr ref android.R.styleable#View_scrollbarStyle
11080     */
11081    @ViewDebug.ExportedProperty(mapping = {
11082            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11083            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11084            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11085            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11086    })
11087    public int getScrollBarStyle() {
11088        return mViewFlags & SCROLLBARS_STYLE_MASK;
11089    }
11090
11091    /**
11092     * <p>Compute the horizontal range that the horizontal scrollbar
11093     * represents.</p>
11094     *
11095     * <p>The range is expressed in arbitrary units that must be the same as the
11096     * units used by {@link #computeHorizontalScrollExtent()} and
11097     * {@link #computeHorizontalScrollOffset()}.</p>
11098     *
11099     * <p>The default range is the drawing width of this view.</p>
11100     *
11101     * @return the total horizontal range represented by the horizontal
11102     *         scrollbar
11103     *
11104     * @see #computeHorizontalScrollExtent()
11105     * @see #computeHorizontalScrollOffset()
11106     * @see android.widget.ScrollBarDrawable
11107     */
11108    protected int computeHorizontalScrollRange() {
11109        return getWidth();
11110    }
11111
11112    /**
11113     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11114     * within the horizontal range. This value is used to compute the position
11115     * of the thumb within the scrollbar's track.</p>
11116     *
11117     * <p>The range is expressed in arbitrary units that must be the same as the
11118     * units used by {@link #computeHorizontalScrollRange()} and
11119     * {@link #computeHorizontalScrollExtent()}.</p>
11120     *
11121     * <p>The default offset is the scroll offset of this view.</p>
11122     *
11123     * @return the horizontal offset of the scrollbar's thumb
11124     *
11125     * @see #computeHorizontalScrollRange()
11126     * @see #computeHorizontalScrollExtent()
11127     * @see android.widget.ScrollBarDrawable
11128     */
11129    protected int computeHorizontalScrollOffset() {
11130        return mScrollX;
11131    }
11132
11133    /**
11134     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11135     * within the horizontal range. This value is used to compute the length
11136     * of the thumb within the scrollbar's track.</p>
11137     *
11138     * <p>The range is expressed in arbitrary units that must be the same as the
11139     * units used by {@link #computeHorizontalScrollRange()} and
11140     * {@link #computeHorizontalScrollOffset()}.</p>
11141     *
11142     * <p>The default extent is the drawing width of this view.</p>
11143     *
11144     * @return the horizontal extent of the scrollbar's thumb
11145     *
11146     * @see #computeHorizontalScrollRange()
11147     * @see #computeHorizontalScrollOffset()
11148     * @see android.widget.ScrollBarDrawable
11149     */
11150    protected int computeHorizontalScrollExtent() {
11151        return getWidth();
11152    }
11153
11154    /**
11155     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11156     *
11157     * <p>The range is expressed in arbitrary units that must be the same as the
11158     * units used by {@link #computeVerticalScrollExtent()} and
11159     * {@link #computeVerticalScrollOffset()}.</p>
11160     *
11161     * @return the total vertical range represented by the vertical scrollbar
11162     *
11163     * <p>The default range is the drawing height of this view.</p>
11164     *
11165     * @see #computeVerticalScrollExtent()
11166     * @see #computeVerticalScrollOffset()
11167     * @see android.widget.ScrollBarDrawable
11168     */
11169    protected int computeVerticalScrollRange() {
11170        return getHeight();
11171    }
11172
11173    /**
11174     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11175     * within the horizontal range. This value is used to compute the position
11176     * of the thumb within the scrollbar's track.</p>
11177     *
11178     * <p>The range is expressed in arbitrary units that must be the same as the
11179     * units used by {@link #computeVerticalScrollRange()} and
11180     * {@link #computeVerticalScrollExtent()}.</p>
11181     *
11182     * <p>The default offset is the scroll offset of this view.</p>
11183     *
11184     * @return the vertical offset of the scrollbar's thumb
11185     *
11186     * @see #computeVerticalScrollRange()
11187     * @see #computeVerticalScrollExtent()
11188     * @see android.widget.ScrollBarDrawable
11189     */
11190    protected int computeVerticalScrollOffset() {
11191        return mScrollY;
11192    }
11193
11194    /**
11195     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11196     * within the vertical range. This value is used to compute the length
11197     * of the thumb within the scrollbar's track.</p>
11198     *
11199     * <p>The range is expressed in arbitrary units that must be the same as the
11200     * units used by {@link #computeVerticalScrollRange()} and
11201     * {@link #computeVerticalScrollOffset()}.</p>
11202     *
11203     * <p>The default extent is the drawing height of this view.</p>
11204     *
11205     * @return the vertical extent of the scrollbar's thumb
11206     *
11207     * @see #computeVerticalScrollRange()
11208     * @see #computeVerticalScrollOffset()
11209     * @see android.widget.ScrollBarDrawable
11210     */
11211    protected int computeVerticalScrollExtent() {
11212        return getHeight();
11213    }
11214
11215    /**
11216     * Check if this view can be scrolled horizontally in a certain direction.
11217     *
11218     * @param direction Negative to check scrolling left, positive to check scrolling right.
11219     * @return true if this view can be scrolled in the specified direction, false otherwise.
11220     */
11221    public boolean canScrollHorizontally(int direction) {
11222        final int offset = computeHorizontalScrollOffset();
11223        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11224        if (range == 0) return false;
11225        if (direction < 0) {
11226            return offset > 0;
11227        } else {
11228            return offset < range - 1;
11229        }
11230    }
11231
11232    /**
11233     * Check if this view can be scrolled vertically in a certain direction.
11234     *
11235     * @param direction Negative to check scrolling up, positive to check scrolling down.
11236     * @return true if this view can be scrolled in the specified direction, false otherwise.
11237     */
11238    public boolean canScrollVertically(int direction) {
11239        final int offset = computeVerticalScrollOffset();
11240        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11241        if (range == 0) return false;
11242        if (direction < 0) {
11243            return offset > 0;
11244        } else {
11245            return offset < range - 1;
11246        }
11247    }
11248
11249    /**
11250     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11251     * scrollbars are painted only if they have been awakened first.</p>
11252     *
11253     * @param canvas the canvas on which to draw the scrollbars
11254     *
11255     * @see #awakenScrollBars(int)
11256     */
11257    protected final void onDrawScrollBars(Canvas canvas) {
11258        // scrollbars are drawn only when the animation is running
11259        final ScrollabilityCache cache = mScrollCache;
11260        if (cache != null) {
11261
11262            int state = cache.state;
11263
11264            if (state == ScrollabilityCache.OFF) {
11265                return;
11266            }
11267
11268            boolean invalidate = false;
11269
11270            if (state == ScrollabilityCache.FADING) {
11271                // We're fading -- get our fade interpolation
11272                if (cache.interpolatorValues == null) {
11273                    cache.interpolatorValues = new float[1];
11274                }
11275
11276                float[] values = cache.interpolatorValues;
11277
11278                // Stops the animation if we're done
11279                if (cache.scrollBarInterpolator.timeToValues(values) ==
11280                        Interpolator.Result.FREEZE_END) {
11281                    cache.state = ScrollabilityCache.OFF;
11282                } else {
11283                    cache.scrollBar.setAlpha(Math.round(values[0]));
11284                }
11285
11286                // This will make the scroll bars inval themselves after
11287                // drawing. We only want this when we're fading so that
11288                // we prevent excessive redraws
11289                invalidate = true;
11290            } else {
11291                // We're just on -- but we may have been fading before so
11292                // reset alpha
11293                cache.scrollBar.setAlpha(255);
11294            }
11295
11296
11297            final int viewFlags = mViewFlags;
11298
11299            final boolean drawHorizontalScrollBar =
11300                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11301            final boolean drawVerticalScrollBar =
11302                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11303                && !isVerticalScrollBarHidden();
11304
11305            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11306                final int width = mRight - mLeft;
11307                final int height = mBottom - mTop;
11308
11309                final ScrollBarDrawable scrollBar = cache.scrollBar;
11310
11311                final int scrollX = mScrollX;
11312                final int scrollY = mScrollY;
11313                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11314
11315                int left, top, right, bottom;
11316
11317                if (drawHorizontalScrollBar) {
11318                    int size = scrollBar.getSize(false);
11319                    if (size <= 0) {
11320                        size = cache.scrollBarSize;
11321                    }
11322
11323                    scrollBar.setParameters(computeHorizontalScrollRange(),
11324                                            computeHorizontalScrollOffset(),
11325                                            computeHorizontalScrollExtent(), false);
11326                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11327                            getVerticalScrollbarWidth() : 0;
11328                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11329                    left = scrollX + (mPaddingLeft & inside);
11330                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11331                    bottom = top + size;
11332                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11333                    if (invalidate) {
11334                        invalidate(left, top, right, bottom);
11335                    }
11336                }
11337
11338                if (drawVerticalScrollBar) {
11339                    int size = scrollBar.getSize(true);
11340                    if (size <= 0) {
11341                        size = cache.scrollBarSize;
11342                    }
11343
11344                    scrollBar.setParameters(computeVerticalScrollRange(),
11345                                            computeVerticalScrollOffset(),
11346                                            computeVerticalScrollExtent(), true);
11347                    switch (mVerticalScrollbarPosition) {
11348                        default:
11349                        case SCROLLBAR_POSITION_DEFAULT:
11350                        case SCROLLBAR_POSITION_RIGHT:
11351                            left = scrollX + width - size - (mUserPaddingRight & inside);
11352                            break;
11353                        case SCROLLBAR_POSITION_LEFT:
11354                            left = scrollX + (mUserPaddingLeft & inside);
11355                            break;
11356                    }
11357                    top = scrollY + (mPaddingTop & inside);
11358                    right = left + size;
11359                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11360                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11361                    if (invalidate) {
11362                        invalidate(left, top, right, bottom);
11363                    }
11364                }
11365            }
11366        }
11367    }
11368
11369    /**
11370     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11371     * FastScroller is visible.
11372     * @return whether to temporarily hide the vertical scrollbar
11373     * @hide
11374     */
11375    protected boolean isVerticalScrollBarHidden() {
11376        return false;
11377    }
11378
11379    /**
11380     * <p>Draw the horizontal scrollbar if
11381     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11382     *
11383     * @param canvas the canvas on which to draw the scrollbar
11384     * @param scrollBar the scrollbar's drawable
11385     *
11386     * @see #isHorizontalScrollBarEnabled()
11387     * @see #computeHorizontalScrollRange()
11388     * @see #computeHorizontalScrollExtent()
11389     * @see #computeHorizontalScrollOffset()
11390     * @see android.widget.ScrollBarDrawable
11391     * @hide
11392     */
11393    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11394            int l, int t, int r, int b) {
11395        scrollBar.setBounds(l, t, r, b);
11396        scrollBar.draw(canvas);
11397    }
11398
11399    /**
11400     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11401     * returns true.</p>
11402     *
11403     * @param canvas the canvas on which to draw the scrollbar
11404     * @param scrollBar the scrollbar's drawable
11405     *
11406     * @see #isVerticalScrollBarEnabled()
11407     * @see #computeVerticalScrollRange()
11408     * @see #computeVerticalScrollExtent()
11409     * @see #computeVerticalScrollOffset()
11410     * @see android.widget.ScrollBarDrawable
11411     * @hide
11412     */
11413    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11414            int l, int t, int r, int b) {
11415        scrollBar.setBounds(l, t, r, b);
11416        scrollBar.draw(canvas);
11417    }
11418
11419    /**
11420     * Implement this to do your drawing.
11421     *
11422     * @param canvas the canvas on which the background will be drawn
11423     */
11424    protected void onDraw(Canvas canvas) {
11425    }
11426
11427    /*
11428     * Caller is responsible for calling requestLayout if necessary.
11429     * (This allows addViewInLayout to not request a new layout.)
11430     */
11431    void assignParent(ViewParent parent) {
11432        if (mParent == null) {
11433            mParent = parent;
11434        } else if (parent == null) {
11435            mParent = null;
11436        } else {
11437            throw new RuntimeException("view " + this + " being added, but"
11438                    + " it already has a parent");
11439        }
11440    }
11441
11442    /**
11443     * This is called when the view is attached to a window.  At this point it
11444     * has a Surface and will start drawing.  Note that this function is
11445     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11446     * however it may be called any time before the first onDraw -- including
11447     * before or after {@link #onMeasure(int, int)}.
11448     *
11449     * @see #onDetachedFromWindow()
11450     */
11451    protected void onAttachedToWindow() {
11452        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11453            mParent.requestTransparentRegion(this);
11454        }
11455
11456        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11457            initialAwakenScrollBars();
11458            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11459        }
11460
11461        jumpDrawablesToCurrentState();
11462
11463        // Order is important here: LayoutDirection MUST be resolved before Padding
11464        // and TextDirection
11465        resolveLayoutDirection();
11466        resolvePadding();
11467        resolveTextDirection();
11468        resolveTextAlignment();
11469
11470        clearAccessibilityFocus();
11471        if (isFocused()) {
11472            InputMethodManager imm = InputMethodManager.peekInstance();
11473            imm.focusIn(this);
11474        }
11475
11476        if (mAttachInfo != null && mDisplayList != null) {
11477            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11478        }
11479    }
11480
11481    /**
11482     * @see #onScreenStateChanged(int)
11483     */
11484    void dispatchScreenStateChanged(int screenState) {
11485        onScreenStateChanged(screenState);
11486    }
11487
11488    /**
11489     * This method is called whenever the state of the screen this view is
11490     * attached to changes. A state change will usually occurs when the screen
11491     * turns on or off (whether it happens automatically or the user does it
11492     * manually.)
11493     *
11494     * @param screenState The new state of the screen. Can be either
11495     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11496     */
11497    public void onScreenStateChanged(int screenState) {
11498    }
11499
11500    /**
11501     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11502     */
11503    private boolean hasRtlSupport() {
11504        return mContext.getApplicationInfo().hasRtlSupport();
11505    }
11506
11507    /**
11508     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11509     * that the parent directionality can and will be resolved before its children.
11510     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11511     * @hide
11512     */
11513    public void resolveLayoutDirection() {
11514        // Clear any previous layout direction resolution
11515        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11516
11517        if (hasRtlSupport()) {
11518            // Set resolved depending on layout direction
11519            switch (getLayoutDirection()) {
11520                case LAYOUT_DIRECTION_INHERIT:
11521                    // If this is root view, no need to look at parent's layout dir.
11522                    if (canResolveLayoutDirection()) {
11523                        ViewGroup viewGroup = ((ViewGroup) mParent);
11524
11525                        if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11526                            mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11527                        }
11528                    } else {
11529                        // Nothing to do, LTR by default
11530                    }
11531                    break;
11532                case LAYOUT_DIRECTION_RTL:
11533                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11534                    break;
11535                case LAYOUT_DIRECTION_LOCALE:
11536                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11537                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11538                    }
11539                    break;
11540                default:
11541                    // Nothing to do, LTR by default
11542            }
11543        }
11544
11545        // Set to resolved
11546        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11547        onResolvedLayoutDirectionChanged();
11548        // Resolve padding
11549        resolvePadding();
11550    }
11551
11552    /**
11553     * Called when layout direction has been resolved.
11554     *
11555     * The default implementation does nothing.
11556     * @hide
11557     */
11558    public void onResolvedLayoutDirectionChanged() {
11559    }
11560
11561    /**
11562     * Resolve padding depending on layout direction.
11563     * @hide
11564     */
11565    public void resolvePadding() {
11566        // If the user specified the absolute padding (either with android:padding or
11567        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11568        // use the default padding or the padding from the background drawable
11569        // (stored at this point in mPadding*)
11570        int resolvedLayoutDirection = getResolvedLayoutDirection();
11571        switch (resolvedLayoutDirection) {
11572            case LAYOUT_DIRECTION_RTL:
11573                // Start user padding override Right user padding. Otherwise, if Right user
11574                // padding is not defined, use the default Right padding. If Right user padding
11575                // is defined, just use it.
11576                if (mUserPaddingStart >= 0) {
11577                    mUserPaddingRight = mUserPaddingStart;
11578                } else if (mUserPaddingRight < 0) {
11579                    mUserPaddingRight = mPaddingRight;
11580                }
11581                if (mUserPaddingEnd >= 0) {
11582                    mUserPaddingLeft = mUserPaddingEnd;
11583                } else if (mUserPaddingLeft < 0) {
11584                    mUserPaddingLeft = mPaddingLeft;
11585                }
11586                break;
11587            case LAYOUT_DIRECTION_LTR:
11588            default:
11589                // Start user padding override Left user padding. Otherwise, if Left user
11590                // padding is not defined, use the default left padding. If Left user padding
11591                // is defined, just use it.
11592                if (mUserPaddingStart >= 0) {
11593                    mUserPaddingLeft = mUserPaddingStart;
11594                } else if (mUserPaddingLeft < 0) {
11595                    mUserPaddingLeft = mPaddingLeft;
11596                }
11597                if (mUserPaddingEnd >= 0) {
11598                    mUserPaddingRight = mUserPaddingEnd;
11599                } else if (mUserPaddingRight < 0) {
11600                    mUserPaddingRight = mPaddingRight;
11601                }
11602        }
11603
11604        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11605
11606        if(isPaddingRelative()) {
11607            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11608        } else {
11609            recomputePadding();
11610        }
11611        onPaddingChanged(resolvedLayoutDirection);
11612    }
11613
11614    /**
11615     * Resolve padding depending on the layout direction. Subclasses that care about
11616     * padding resolution should override this method. The default implementation does
11617     * nothing.
11618     *
11619     * @param layoutDirection the direction of the layout
11620     *
11621     * @see {@link #LAYOUT_DIRECTION_LTR}
11622     * @see {@link #LAYOUT_DIRECTION_RTL}
11623     * @hide
11624     */
11625    public void onPaddingChanged(int layoutDirection) {
11626    }
11627
11628    /**
11629     * Check if layout direction resolution can be done.
11630     *
11631     * @return true if layout direction resolution can be done otherwise return false.
11632     * @hide
11633     */
11634    public boolean canResolveLayoutDirection() {
11635        switch (getLayoutDirection()) {
11636            case LAYOUT_DIRECTION_INHERIT:
11637                return (mParent != null) && (mParent instanceof ViewGroup);
11638            default:
11639                return true;
11640        }
11641    }
11642
11643    /**
11644     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11645     * when reset is done.
11646     * @hide
11647     */
11648    public void resetResolvedLayoutDirection() {
11649        // Reset the current resolved bits
11650        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11651        onResolvedLayoutDirectionReset();
11652        // Reset also the text direction
11653        resetResolvedTextDirection();
11654    }
11655
11656    /**
11657     * Called during reset of resolved layout direction.
11658     *
11659     * Subclasses need to override this method to clear cached information that depends on the
11660     * resolved layout direction, or to inform child views that inherit their layout direction.
11661     *
11662     * The default implementation does nothing.
11663     * @hide
11664     */
11665    public void onResolvedLayoutDirectionReset() {
11666    }
11667
11668    /**
11669     * Check if a Locale uses an RTL script.
11670     *
11671     * @param locale Locale to check
11672     * @return true if the Locale uses an RTL script.
11673     * @hide
11674     */
11675    protected static boolean isLayoutDirectionRtl(Locale locale) {
11676        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11677    }
11678
11679    /**
11680     * This is called when the view is detached from a window.  At this point it
11681     * no longer has a surface for drawing.
11682     *
11683     * @see #onAttachedToWindow()
11684     */
11685    protected void onDetachedFromWindow() {
11686        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11687
11688        removeUnsetPressCallback();
11689        removeLongPressCallback();
11690        removePerformClickCallback();
11691        removeSendViewScrolledAccessibilityEventCallback();
11692
11693        destroyDrawingCache();
11694
11695        destroyLayer(false);
11696
11697        if (mAttachInfo != null) {
11698            if (mDisplayList != null) {
11699                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11700            }
11701            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11702        } else {
11703            // Should never happen
11704            clearDisplayList();
11705        }
11706
11707        mCurrentAnimation = null;
11708
11709        resetResolvedLayoutDirection();
11710        resetResolvedTextAlignment();
11711        resetAccessibilityStateChanged();
11712    }
11713
11714    /**
11715     * @return The number of times this view has been attached to a window
11716     */
11717    protected int getWindowAttachCount() {
11718        return mWindowAttachCount;
11719    }
11720
11721    /**
11722     * Retrieve a unique token identifying the window this view is attached to.
11723     * @return Return the window's token for use in
11724     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11725     */
11726    public IBinder getWindowToken() {
11727        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11728    }
11729
11730    /**
11731     * Retrieve a unique token identifying the top-level "real" window of
11732     * the window that this view is attached to.  That is, this is like
11733     * {@link #getWindowToken}, except if the window this view in is a panel
11734     * window (attached to another containing window), then the token of
11735     * the containing window is returned instead.
11736     *
11737     * @return Returns the associated window token, either
11738     * {@link #getWindowToken()} or the containing window's token.
11739     */
11740    public IBinder getApplicationWindowToken() {
11741        AttachInfo ai = mAttachInfo;
11742        if (ai != null) {
11743            IBinder appWindowToken = ai.mPanelParentWindowToken;
11744            if (appWindowToken == null) {
11745                appWindowToken = ai.mWindowToken;
11746            }
11747            return appWindowToken;
11748        }
11749        return null;
11750    }
11751
11752    /**
11753     * Retrieve private session object this view hierarchy is using to
11754     * communicate with the window manager.
11755     * @return the session object to communicate with the window manager
11756     */
11757    /*package*/ IWindowSession getWindowSession() {
11758        return mAttachInfo != null ? mAttachInfo.mSession : null;
11759    }
11760
11761    /**
11762     * @param info the {@link android.view.View.AttachInfo} to associated with
11763     *        this view
11764     */
11765    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11766        //System.out.println("Attached! " + this);
11767        mAttachInfo = info;
11768        mWindowAttachCount++;
11769        // We will need to evaluate the drawable state at least once.
11770        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11771        if (mFloatingTreeObserver != null) {
11772            info.mTreeObserver.merge(mFloatingTreeObserver);
11773            mFloatingTreeObserver = null;
11774        }
11775        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11776            mAttachInfo.mScrollContainers.add(this);
11777            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11778        }
11779        performCollectViewAttributes(mAttachInfo, visibility);
11780        onAttachedToWindow();
11781
11782        ListenerInfo li = mListenerInfo;
11783        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11784                li != null ? li.mOnAttachStateChangeListeners : null;
11785        if (listeners != null && listeners.size() > 0) {
11786            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11787            // perform the dispatching. The iterator is a safe guard against listeners that
11788            // could mutate the list by calling the various add/remove methods. This prevents
11789            // the array from being modified while we iterate it.
11790            for (OnAttachStateChangeListener listener : listeners) {
11791                listener.onViewAttachedToWindow(this);
11792            }
11793        }
11794
11795        int vis = info.mWindowVisibility;
11796        if (vis != GONE) {
11797            onWindowVisibilityChanged(vis);
11798        }
11799        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11800            // If nobody has evaluated the drawable state yet, then do it now.
11801            refreshDrawableState();
11802        }
11803    }
11804
11805    void dispatchDetachedFromWindow() {
11806        AttachInfo info = mAttachInfo;
11807        if (info != null) {
11808            int vis = info.mWindowVisibility;
11809            if (vis != GONE) {
11810                onWindowVisibilityChanged(GONE);
11811            }
11812        }
11813
11814        onDetachedFromWindow();
11815
11816        ListenerInfo li = mListenerInfo;
11817        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11818                li != null ? li.mOnAttachStateChangeListeners : null;
11819        if (listeners != null && listeners.size() > 0) {
11820            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11821            // perform the dispatching. The iterator is a safe guard against listeners that
11822            // could mutate the list by calling the various add/remove methods. This prevents
11823            // the array from being modified while we iterate it.
11824            for (OnAttachStateChangeListener listener : listeners) {
11825                listener.onViewDetachedFromWindow(this);
11826            }
11827        }
11828
11829        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11830            mAttachInfo.mScrollContainers.remove(this);
11831            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11832        }
11833
11834        mAttachInfo = null;
11835    }
11836
11837    /**
11838     * Store this view hierarchy's frozen state into the given container.
11839     *
11840     * @param container The SparseArray in which to save the view's state.
11841     *
11842     * @see #restoreHierarchyState(android.util.SparseArray)
11843     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11844     * @see #onSaveInstanceState()
11845     */
11846    public void saveHierarchyState(SparseArray<Parcelable> container) {
11847        dispatchSaveInstanceState(container);
11848    }
11849
11850    /**
11851     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11852     * this view and its children. May be overridden to modify how freezing happens to a
11853     * view's children; for example, some views may want to not store state for their children.
11854     *
11855     * @param container The SparseArray in which to save the view's state.
11856     *
11857     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11858     * @see #saveHierarchyState(android.util.SparseArray)
11859     * @see #onSaveInstanceState()
11860     */
11861    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11862        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11863            mPrivateFlags &= ~SAVE_STATE_CALLED;
11864            Parcelable state = onSaveInstanceState();
11865            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11866                throw new IllegalStateException(
11867                        "Derived class did not call super.onSaveInstanceState()");
11868            }
11869            if (state != null) {
11870                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11871                // + ": " + state);
11872                container.put(mID, state);
11873            }
11874        }
11875    }
11876
11877    /**
11878     * Hook allowing a view to generate a representation of its internal state
11879     * that can later be used to create a new instance with that same state.
11880     * This state should only contain information that is not persistent or can
11881     * not be reconstructed later. For example, you will never store your
11882     * current position on screen because that will be computed again when a
11883     * new instance of the view is placed in its view hierarchy.
11884     * <p>
11885     * Some examples of things you may store here: the current cursor position
11886     * in a text view (but usually not the text itself since that is stored in a
11887     * content provider or other persistent storage), the currently selected
11888     * item in a list view.
11889     *
11890     * @return Returns a Parcelable object containing the view's current dynamic
11891     *         state, or null if there is nothing interesting to save. The
11892     *         default implementation returns null.
11893     * @see #onRestoreInstanceState(android.os.Parcelable)
11894     * @see #saveHierarchyState(android.util.SparseArray)
11895     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11896     * @see #setSaveEnabled(boolean)
11897     */
11898    protected Parcelable onSaveInstanceState() {
11899        mPrivateFlags |= SAVE_STATE_CALLED;
11900        return BaseSavedState.EMPTY_STATE;
11901    }
11902
11903    /**
11904     * Restore this view hierarchy's frozen state from the given container.
11905     *
11906     * @param container The SparseArray which holds previously frozen states.
11907     *
11908     * @see #saveHierarchyState(android.util.SparseArray)
11909     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11910     * @see #onRestoreInstanceState(android.os.Parcelable)
11911     */
11912    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11913        dispatchRestoreInstanceState(container);
11914    }
11915
11916    /**
11917     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11918     * state for this view and its children. May be overridden to modify how restoring
11919     * happens to a view's children; for example, some views may want to not store state
11920     * for their children.
11921     *
11922     * @param container The SparseArray which holds previously saved state.
11923     *
11924     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11925     * @see #restoreHierarchyState(android.util.SparseArray)
11926     * @see #onRestoreInstanceState(android.os.Parcelable)
11927     */
11928    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11929        if (mID != NO_ID) {
11930            Parcelable state = container.get(mID);
11931            if (state != null) {
11932                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11933                // + ": " + state);
11934                mPrivateFlags &= ~SAVE_STATE_CALLED;
11935                onRestoreInstanceState(state);
11936                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11937                    throw new IllegalStateException(
11938                            "Derived class did not call super.onRestoreInstanceState()");
11939                }
11940            }
11941        }
11942    }
11943
11944    /**
11945     * Hook allowing a view to re-apply a representation of its internal state that had previously
11946     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11947     * null state.
11948     *
11949     * @param state The frozen state that had previously been returned by
11950     *        {@link #onSaveInstanceState}.
11951     *
11952     * @see #onSaveInstanceState()
11953     * @see #restoreHierarchyState(android.util.SparseArray)
11954     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11955     */
11956    protected void onRestoreInstanceState(Parcelable state) {
11957        mPrivateFlags |= SAVE_STATE_CALLED;
11958        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11959            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11960                    + "received " + state.getClass().toString() + " instead. This usually happens "
11961                    + "when two views of different type have the same id in the same hierarchy. "
11962                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11963                    + "other views do not use the same id.");
11964        }
11965    }
11966
11967    /**
11968     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11969     *
11970     * @return the drawing start time in milliseconds
11971     */
11972    public long getDrawingTime() {
11973        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11974    }
11975
11976    /**
11977     * <p>Enables or disables the duplication of the parent's state into this view. When
11978     * duplication is enabled, this view gets its drawable state from its parent rather
11979     * than from its own internal properties.</p>
11980     *
11981     * <p>Note: in the current implementation, setting this property to true after the
11982     * view was added to a ViewGroup might have no effect at all. This property should
11983     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11984     *
11985     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11986     * property is enabled, an exception will be thrown.</p>
11987     *
11988     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11989     * parent, these states should not be affected by this method.</p>
11990     *
11991     * @param enabled True to enable duplication of the parent's drawable state, false
11992     *                to disable it.
11993     *
11994     * @see #getDrawableState()
11995     * @see #isDuplicateParentStateEnabled()
11996     */
11997    public void setDuplicateParentStateEnabled(boolean enabled) {
11998        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11999    }
12000
12001    /**
12002     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12003     *
12004     * @return True if this view's drawable state is duplicated from the parent,
12005     *         false otherwise
12006     *
12007     * @see #getDrawableState()
12008     * @see #setDuplicateParentStateEnabled(boolean)
12009     */
12010    public boolean isDuplicateParentStateEnabled() {
12011        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12012    }
12013
12014    /**
12015     * <p>Specifies the type of layer backing this view. The layer can be
12016     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12017     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12018     *
12019     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12020     * instance that controls how the layer is composed on screen. The following
12021     * properties of the paint are taken into account when composing the layer:</p>
12022     * <ul>
12023     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12024     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12025     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12026     * </ul>
12027     *
12028     * <p>If this view has an alpha value set to < 1.0 by calling
12029     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12030     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12031     * equivalent to setting a hardware layer on this view and providing a paint with
12032     * the desired alpha value.<p>
12033     *
12034     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
12035     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
12036     * for more information on when and how to use layers.</p>
12037     *
12038     * @param layerType The ype of layer to use with this view, must be one of
12039     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12040     *        {@link #LAYER_TYPE_HARDWARE}
12041     * @param paint The paint used to compose the layer. This argument is optional
12042     *        and can be null. It is ignored when the layer type is
12043     *        {@link #LAYER_TYPE_NONE}
12044     *
12045     * @see #getLayerType()
12046     * @see #LAYER_TYPE_NONE
12047     * @see #LAYER_TYPE_SOFTWARE
12048     * @see #LAYER_TYPE_HARDWARE
12049     * @see #setAlpha(float)
12050     *
12051     * @attr ref android.R.styleable#View_layerType
12052     */
12053    public void setLayerType(int layerType, Paint paint) {
12054        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12055            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12056                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12057        }
12058
12059        if (layerType == mLayerType) {
12060            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12061                mLayerPaint = paint == null ? new Paint() : paint;
12062                invalidateParentCaches();
12063                invalidate(true);
12064            }
12065            return;
12066        }
12067
12068        // Destroy any previous software drawing cache if needed
12069        switch (mLayerType) {
12070            case LAYER_TYPE_HARDWARE:
12071                destroyLayer(false);
12072                // fall through - non-accelerated views may use software layer mechanism instead
12073            case LAYER_TYPE_SOFTWARE:
12074                destroyDrawingCache();
12075                break;
12076            default:
12077                break;
12078        }
12079
12080        mLayerType = layerType;
12081        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12082        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12083        mLocalDirtyRect = layerDisabled ? null : new Rect();
12084
12085        invalidateParentCaches();
12086        invalidate(true);
12087    }
12088
12089    /**
12090     * Indicates whether this view has a static layer. A view with layer type
12091     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12092     * dynamic.
12093     */
12094    boolean hasStaticLayer() {
12095        return true;
12096    }
12097
12098    /**
12099     * Indicates what type of layer is currently associated with this view. By default
12100     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12101     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12102     * for more information on the different types of layers.
12103     *
12104     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12105     *         {@link #LAYER_TYPE_HARDWARE}
12106     *
12107     * @see #setLayerType(int, android.graphics.Paint)
12108     * @see #buildLayer()
12109     * @see #LAYER_TYPE_NONE
12110     * @see #LAYER_TYPE_SOFTWARE
12111     * @see #LAYER_TYPE_HARDWARE
12112     */
12113    public int getLayerType() {
12114        return mLayerType;
12115    }
12116
12117    /**
12118     * Forces this view's layer to be created and this view to be rendered
12119     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12120     * invoking this method will have no effect.
12121     *
12122     * This method can for instance be used to render a view into its layer before
12123     * starting an animation. If this view is complex, rendering into the layer
12124     * before starting the animation will avoid skipping frames.
12125     *
12126     * @throws IllegalStateException If this view is not attached to a window
12127     *
12128     * @see #setLayerType(int, android.graphics.Paint)
12129     */
12130    public void buildLayer() {
12131        if (mLayerType == LAYER_TYPE_NONE) return;
12132
12133        if (mAttachInfo == null) {
12134            throw new IllegalStateException("This view must be attached to a window first");
12135        }
12136
12137        switch (mLayerType) {
12138            case LAYER_TYPE_HARDWARE:
12139                if (mAttachInfo.mHardwareRenderer != null &&
12140                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12141                        mAttachInfo.mHardwareRenderer.validate()) {
12142                    getHardwareLayer();
12143                }
12144                break;
12145            case LAYER_TYPE_SOFTWARE:
12146                buildDrawingCache(true);
12147                break;
12148        }
12149    }
12150
12151    // Make sure the HardwareRenderer.validate() was invoked before calling this method
12152    void flushLayer() {
12153        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
12154            mHardwareLayer.flush();
12155        }
12156    }
12157
12158    /**
12159     * <p>Returns a hardware layer that can be used to draw this view again
12160     * without executing its draw method.</p>
12161     *
12162     * @return A HardwareLayer ready to render, or null if an error occurred.
12163     */
12164    HardwareLayer getHardwareLayer() {
12165        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12166                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12167            return null;
12168        }
12169
12170        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12171
12172        final int width = mRight - mLeft;
12173        final int height = mBottom - mTop;
12174
12175        if (width == 0 || height == 0) {
12176            return null;
12177        }
12178
12179        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12180            if (mHardwareLayer == null) {
12181                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12182                        width, height, isOpaque());
12183                mLocalDirtyRect.set(0, 0, width, height);
12184            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12185                mHardwareLayer.resize(width, height);
12186                mLocalDirtyRect.set(0, 0, width, height);
12187            }
12188
12189            // The layer is not valid if the underlying GPU resources cannot be allocated
12190            if (!mHardwareLayer.isValid()) {
12191                return null;
12192            }
12193
12194            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12195            mLocalDirtyRect.setEmpty();
12196        }
12197
12198        return mHardwareLayer;
12199    }
12200
12201    /**
12202     * Destroys this View's hardware layer if possible.
12203     *
12204     * @return True if the layer was destroyed, false otherwise.
12205     *
12206     * @see #setLayerType(int, android.graphics.Paint)
12207     * @see #LAYER_TYPE_HARDWARE
12208     */
12209    boolean destroyLayer(boolean valid) {
12210        if (mHardwareLayer != null) {
12211            AttachInfo info = mAttachInfo;
12212            if (info != null && info.mHardwareRenderer != null &&
12213                    info.mHardwareRenderer.isEnabled() &&
12214                    (valid || info.mHardwareRenderer.validate())) {
12215                mHardwareLayer.destroy();
12216                mHardwareLayer = null;
12217
12218                invalidate(true);
12219                invalidateParentCaches();
12220            }
12221            return true;
12222        }
12223        return false;
12224    }
12225
12226    /**
12227     * Destroys all hardware rendering resources. This method is invoked
12228     * when the system needs to reclaim resources. Upon execution of this
12229     * method, you should free any OpenGL resources created by the view.
12230     *
12231     * Note: you <strong>must</strong> call
12232     * <code>super.destroyHardwareResources()</code> when overriding
12233     * this method.
12234     *
12235     * @hide
12236     */
12237    protected void destroyHardwareResources() {
12238        destroyLayer(true);
12239    }
12240
12241    /**
12242     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12243     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12244     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12245     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12246     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12247     * null.</p>
12248     *
12249     * <p>Enabling the drawing cache is similar to
12250     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12251     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12252     * drawing cache has no effect on rendering because the system uses a different mechanism
12253     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12254     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12255     * for information on how to enable software and hardware layers.</p>
12256     *
12257     * <p>This API can be used to manually generate
12258     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12259     * {@link #getDrawingCache()}.</p>
12260     *
12261     * @param enabled true to enable the drawing cache, false otherwise
12262     *
12263     * @see #isDrawingCacheEnabled()
12264     * @see #getDrawingCache()
12265     * @see #buildDrawingCache()
12266     * @see #setLayerType(int, android.graphics.Paint)
12267     */
12268    public void setDrawingCacheEnabled(boolean enabled) {
12269        mCachingFailed = false;
12270        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12271    }
12272
12273    /**
12274     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12275     *
12276     * @return true if the drawing cache is enabled
12277     *
12278     * @see #setDrawingCacheEnabled(boolean)
12279     * @see #getDrawingCache()
12280     */
12281    @ViewDebug.ExportedProperty(category = "drawing")
12282    public boolean isDrawingCacheEnabled() {
12283        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12284    }
12285
12286    /**
12287     * Debugging utility which recursively outputs the dirty state of a view and its
12288     * descendants.
12289     *
12290     * @hide
12291     */
12292    @SuppressWarnings({"UnusedDeclaration"})
12293    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12294        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12295                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12296                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12297                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12298        if (clear) {
12299            mPrivateFlags &= clearMask;
12300        }
12301        if (this instanceof ViewGroup) {
12302            ViewGroup parent = (ViewGroup) this;
12303            final int count = parent.getChildCount();
12304            for (int i = 0; i < count; i++) {
12305                final View child = parent.getChildAt(i);
12306                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12307            }
12308        }
12309    }
12310
12311    /**
12312     * This method is used by ViewGroup to cause its children to restore or recreate their
12313     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12314     * to recreate its own display list, which would happen if it went through the normal
12315     * draw/dispatchDraw mechanisms.
12316     *
12317     * @hide
12318     */
12319    protected void dispatchGetDisplayList() {}
12320
12321    /**
12322     * A view that is not attached or hardware accelerated cannot create a display list.
12323     * This method checks these conditions and returns the appropriate result.
12324     *
12325     * @return true if view has the ability to create a display list, false otherwise.
12326     *
12327     * @hide
12328     */
12329    public boolean canHaveDisplayList() {
12330        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12331    }
12332
12333    /**
12334     * @return The HardwareRenderer associated with that view or null if hardware rendering
12335     * is not supported or this this has not been attached to a window.
12336     *
12337     * @hide
12338     */
12339    public HardwareRenderer getHardwareRenderer() {
12340        if (mAttachInfo != null) {
12341            return mAttachInfo.mHardwareRenderer;
12342        }
12343        return null;
12344    }
12345
12346    /**
12347     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12348     * Otherwise, the same display list will be returned (after having been rendered into
12349     * along the way, depending on the invalidation state of the view).
12350     *
12351     * @param displayList The previous version of this displayList, could be null.
12352     * @param isLayer Whether the requester of the display list is a layer. If so,
12353     * the view will avoid creating a layer inside the resulting display list.
12354     * @return A new or reused DisplayList object.
12355     */
12356    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12357        if (!canHaveDisplayList()) {
12358            return null;
12359        }
12360
12361        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12362                displayList == null || !displayList.isValid() ||
12363                (!isLayer && mRecreateDisplayList))) {
12364            // Don't need to recreate the display list, just need to tell our
12365            // children to restore/recreate theirs
12366            if (displayList != null && displayList.isValid() &&
12367                    !isLayer && !mRecreateDisplayList) {
12368                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12369                mPrivateFlags &= ~DIRTY_MASK;
12370                dispatchGetDisplayList();
12371
12372                return displayList;
12373            }
12374
12375            if (!isLayer) {
12376                // If we got here, we're recreating it. Mark it as such to ensure that
12377                // we copy in child display lists into ours in drawChild()
12378                mRecreateDisplayList = true;
12379            }
12380            if (displayList == null) {
12381                final String name = getClass().getSimpleName();
12382                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12383                // If we're creating a new display list, make sure our parent gets invalidated
12384                // since they will need to recreate their display list to account for this
12385                // new child display list.
12386                invalidateParentCaches();
12387            }
12388
12389            boolean caching = false;
12390            final HardwareCanvas canvas = displayList.start();
12391            int width = mRight - mLeft;
12392            int height = mBottom - mTop;
12393
12394            try {
12395                canvas.setViewport(width, height);
12396                // The dirty rect should always be null for a display list
12397                canvas.onPreDraw(null);
12398                int layerType = (
12399                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
12400                        getLayerType() : LAYER_TYPE_NONE;
12401                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12402                    if (layerType == LAYER_TYPE_HARDWARE) {
12403                        final HardwareLayer layer = getHardwareLayer();
12404                        if (layer != null && layer.isValid()) {
12405                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12406                        } else {
12407                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12408                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12409                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12410                        }
12411                        caching = true;
12412                    } else {
12413                        buildDrawingCache(true);
12414                        Bitmap cache = getDrawingCache(true);
12415                        if (cache != null) {
12416                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12417                            caching = true;
12418                        }
12419                    }
12420                } else {
12421
12422                    computeScroll();
12423
12424                    canvas.translate(-mScrollX, -mScrollY);
12425                    if (!isLayer) {
12426                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12427                        mPrivateFlags &= ~DIRTY_MASK;
12428                    }
12429
12430                    // Fast path for layouts with no backgrounds
12431                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12432                        dispatchDraw(canvas);
12433                    } else {
12434                        draw(canvas);
12435                    }
12436                }
12437            } finally {
12438                canvas.onPostDraw();
12439
12440                displayList.end();
12441                displayList.setCaching(caching);
12442                if (isLayer) {
12443                    displayList.setLeftTopRightBottom(0, 0, width, height);
12444                } else {
12445                    setDisplayListProperties(displayList);
12446                }
12447            }
12448        } else if (!isLayer) {
12449            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12450            mPrivateFlags &= ~DIRTY_MASK;
12451        }
12452
12453        return displayList;
12454    }
12455
12456    /**
12457     * Get the DisplayList for the HardwareLayer
12458     *
12459     * @param layer The HardwareLayer whose DisplayList we want
12460     * @return A DisplayList fopr the specified HardwareLayer
12461     */
12462    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12463        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12464        layer.setDisplayList(displayList);
12465        return displayList;
12466    }
12467
12468
12469    /**
12470     * <p>Returns a display list that can be used to draw this view again
12471     * without executing its draw method.</p>
12472     *
12473     * @return A DisplayList ready to replay, or null if caching is not enabled.
12474     *
12475     * @hide
12476     */
12477    public DisplayList getDisplayList() {
12478        mDisplayList = getDisplayList(mDisplayList, false);
12479        return mDisplayList;
12480    }
12481
12482    private void clearDisplayList() {
12483        if (mDisplayList != null) {
12484            mDisplayList.invalidate();
12485            mDisplayList.clear();
12486        }
12487    }
12488
12489    /**
12490     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12491     *
12492     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12493     *
12494     * @see #getDrawingCache(boolean)
12495     */
12496    public Bitmap getDrawingCache() {
12497        return getDrawingCache(false);
12498    }
12499
12500    /**
12501     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12502     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12503     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12504     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12505     * request the drawing cache by calling this method and draw it on screen if the
12506     * returned bitmap is not null.</p>
12507     *
12508     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12509     * this method will create a bitmap of the same size as this view. Because this bitmap
12510     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12511     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12512     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12513     * size than the view. This implies that your application must be able to handle this
12514     * size.</p>
12515     *
12516     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12517     *        the current density of the screen when the application is in compatibility
12518     *        mode.
12519     *
12520     * @return A bitmap representing this view or null if cache is disabled.
12521     *
12522     * @see #setDrawingCacheEnabled(boolean)
12523     * @see #isDrawingCacheEnabled()
12524     * @see #buildDrawingCache(boolean)
12525     * @see #destroyDrawingCache()
12526     */
12527    public Bitmap getDrawingCache(boolean autoScale) {
12528        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12529            return null;
12530        }
12531        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12532            buildDrawingCache(autoScale);
12533        }
12534        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12535    }
12536
12537    /**
12538     * <p>Frees the resources used by the drawing cache. If you call
12539     * {@link #buildDrawingCache()} manually without calling
12540     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12541     * should cleanup the cache with this method afterwards.</p>
12542     *
12543     * @see #setDrawingCacheEnabled(boolean)
12544     * @see #buildDrawingCache()
12545     * @see #getDrawingCache()
12546     */
12547    public void destroyDrawingCache() {
12548        if (mDrawingCache != null) {
12549            mDrawingCache.recycle();
12550            mDrawingCache = null;
12551        }
12552        if (mUnscaledDrawingCache != null) {
12553            mUnscaledDrawingCache.recycle();
12554            mUnscaledDrawingCache = null;
12555        }
12556    }
12557
12558    /**
12559     * Setting a solid background color for the drawing cache's bitmaps will improve
12560     * performance and memory usage. Note, though that this should only be used if this
12561     * view will always be drawn on top of a solid color.
12562     *
12563     * @param color The background color to use for the drawing cache's bitmap
12564     *
12565     * @see #setDrawingCacheEnabled(boolean)
12566     * @see #buildDrawingCache()
12567     * @see #getDrawingCache()
12568     */
12569    public void setDrawingCacheBackgroundColor(int color) {
12570        if (color != mDrawingCacheBackgroundColor) {
12571            mDrawingCacheBackgroundColor = color;
12572            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12573        }
12574    }
12575
12576    /**
12577     * @see #setDrawingCacheBackgroundColor(int)
12578     *
12579     * @return The background color to used for the drawing cache's bitmap
12580     */
12581    public int getDrawingCacheBackgroundColor() {
12582        return mDrawingCacheBackgroundColor;
12583    }
12584
12585    /**
12586     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12587     *
12588     * @see #buildDrawingCache(boolean)
12589     */
12590    public void buildDrawingCache() {
12591        buildDrawingCache(false);
12592    }
12593
12594    /**
12595     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12596     *
12597     * <p>If you call {@link #buildDrawingCache()} manually without calling
12598     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12599     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12600     *
12601     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12602     * this method will create a bitmap of the same size as this view. Because this bitmap
12603     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12604     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12605     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12606     * size than the view. This implies that your application must be able to handle this
12607     * size.</p>
12608     *
12609     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12610     * you do not need the drawing cache bitmap, calling this method will increase memory
12611     * usage and cause the view to be rendered in software once, thus negatively impacting
12612     * performance.</p>
12613     *
12614     * @see #getDrawingCache()
12615     * @see #destroyDrawingCache()
12616     */
12617    public void buildDrawingCache(boolean autoScale) {
12618        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12619                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12620            mCachingFailed = false;
12621
12622            int width = mRight - mLeft;
12623            int height = mBottom - mTop;
12624
12625            final AttachInfo attachInfo = mAttachInfo;
12626            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12627
12628            if (autoScale && scalingRequired) {
12629                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12630                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12631            }
12632
12633            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12634            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12635            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12636
12637            if (width <= 0 || height <= 0 ||
12638                     // Projected bitmap size in bytes
12639                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12640                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12641                destroyDrawingCache();
12642                mCachingFailed = true;
12643                return;
12644            }
12645
12646            boolean clear = true;
12647            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12648
12649            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12650                Bitmap.Config quality;
12651                if (!opaque) {
12652                    // Never pick ARGB_4444 because it looks awful
12653                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12654                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12655                        case DRAWING_CACHE_QUALITY_AUTO:
12656                            quality = Bitmap.Config.ARGB_8888;
12657                            break;
12658                        case DRAWING_CACHE_QUALITY_LOW:
12659                            quality = Bitmap.Config.ARGB_8888;
12660                            break;
12661                        case DRAWING_CACHE_QUALITY_HIGH:
12662                            quality = Bitmap.Config.ARGB_8888;
12663                            break;
12664                        default:
12665                            quality = Bitmap.Config.ARGB_8888;
12666                            break;
12667                    }
12668                } else {
12669                    // Optimization for translucent windows
12670                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12671                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12672                }
12673
12674                // Try to cleanup memory
12675                if (bitmap != null) bitmap.recycle();
12676
12677                try {
12678                    bitmap = Bitmap.createBitmap(width, height, quality);
12679                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12680                    if (autoScale) {
12681                        mDrawingCache = bitmap;
12682                    } else {
12683                        mUnscaledDrawingCache = bitmap;
12684                    }
12685                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12686                } catch (OutOfMemoryError e) {
12687                    // If there is not enough memory to create the bitmap cache, just
12688                    // ignore the issue as bitmap caches are not required to draw the
12689                    // view hierarchy
12690                    if (autoScale) {
12691                        mDrawingCache = null;
12692                    } else {
12693                        mUnscaledDrawingCache = null;
12694                    }
12695                    mCachingFailed = true;
12696                    return;
12697                }
12698
12699                clear = drawingCacheBackgroundColor != 0;
12700            }
12701
12702            Canvas canvas;
12703            if (attachInfo != null) {
12704                canvas = attachInfo.mCanvas;
12705                if (canvas == null) {
12706                    canvas = new Canvas();
12707                }
12708                canvas.setBitmap(bitmap);
12709                // Temporarily clobber the cached Canvas in case one of our children
12710                // is also using a drawing cache. Without this, the children would
12711                // steal the canvas by attaching their own bitmap to it and bad, bad
12712                // thing would happen (invisible views, corrupted drawings, etc.)
12713                attachInfo.mCanvas = null;
12714            } else {
12715                // This case should hopefully never or seldom happen
12716                canvas = new Canvas(bitmap);
12717            }
12718
12719            if (clear) {
12720                bitmap.eraseColor(drawingCacheBackgroundColor);
12721            }
12722
12723            computeScroll();
12724            final int restoreCount = canvas.save();
12725
12726            if (autoScale && scalingRequired) {
12727                final float scale = attachInfo.mApplicationScale;
12728                canvas.scale(scale, scale);
12729            }
12730
12731            canvas.translate(-mScrollX, -mScrollY);
12732
12733            mPrivateFlags |= DRAWN;
12734            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12735                    mLayerType != LAYER_TYPE_NONE) {
12736                mPrivateFlags |= DRAWING_CACHE_VALID;
12737            }
12738
12739            // Fast path for layouts with no backgrounds
12740            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12741                mPrivateFlags &= ~DIRTY_MASK;
12742                dispatchDraw(canvas);
12743            } else {
12744                draw(canvas);
12745            }
12746
12747            canvas.restoreToCount(restoreCount);
12748            canvas.setBitmap(null);
12749
12750            if (attachInfo != null) {
12751                // Restore the cached Canvas for our siblings
12752                attachInfo.mCanvas = canvas;
12753            }
12754        }
12755    }
12756
12757    /**
12758     * Create a snapshot of the view into a bitmap.  We should probably make
12759     * some form of this public, but should think about the API.
12760     */
12761    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12762        int width = mRight - mLeft;
12763        int height = mBottom - mTop;
12764
12765        final AttachInfo attachInfo = mAttachInfo;
12766        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12767        width = (int) ((width * scale) + 0.5f);
12768        height = (int) ((height * scale) + 0.5f);
12769
12770        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12771        if (bitmap == null) {
12772            throw new OutOfMemoryError();
12773        }
12774
12775        Resources resources = getResources();
12776        if (resources != null) {
12777            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12778        }
12779
12780        Canvas canvas;
12781        if (attachInfo != null) {
12782            canvas = attachInfo.mCanvas;
12783            if (canvas == null) {
12784                canvas = new Canvas();
12785            }
12786            canvas.setBitmap(bitmap);
12787            // Temporarily clobber the cached Canvas in case one of our children
12788            // is also using a drawing cache. Without this, the children would
12789            // steal the canvas by attaching their own bitmap to it and bad, bad
12790            // things would happen (invisible views, corrupted drawings, etc.)
12791            attachInfo.mCanvas = null;
12792        } else {
12793            // This case should hopefully never or seldom happen
12794            canvas = new Canvas(bitmap);
12795        }
12796
12797        if ((backgroundColor & 0xff000000) != 0) {
12798            bitmap.eraseColor(backgroundColor);
12799        }
12800
12801        computeScroll();
12802        final int restoreCount = canvas.save();
12803        canvas.scale(scale, scale);
12804        canvas.translate(-mScrollX, -mScrollY);
12805
12806        // Temporarily remove the dirty mask
12807        int flags = mPrivateFlags;
12808        mPrivateFlags &= ~DIRTY_MASK;
12809
12810        // Fast path for layouts with no backgrounds
12811        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12812            dispatchDraw(canvas);
12813        } else {
12814            draw(canvas);
12815        }
12816
12817        mPrivateFlags = flags;
12818
12819        canvas.restoreToCount(restoreCount);
12820        canvas.setBitmap(null);
12821
12822        if (attachInfo != null) {
12823            // Restore the cached Canvas for our siblings
12824            attachInfo.mCanvas = canvas;
12825        }
12826
12827        return bitmap;
12828    }
12829
12830    /**
12831     * Indicates whether this View is currently in edit mode. A View is usually
12832     * in edit mode when displayed within a developer tool. For instance, if
12833     * this View is being drawn by a visual user interface builder, this method
12834     * should return true.
12835     *
12836     * Subclasses should check the return value of this method to provide
12837     * different behaviors if their normal behavior might interfere with the
12838     * host environment. For instance: the class spawns a thread in its
12839     * constructor, the drawing code relies on device-specific features, etc.
12840     *
12841     * This method is usually checked in the drawing code of custom widgets.
12842     *
12843     * @return True if this View is in edit mode, false otherwise.
12844     */
12845    public boolean isInEditMode() {
12846        return false;
12847    }
12848
12849    /**
12850     * If the View draws content inside its padding and enables fading edges,
12851     * it needs to support padding offsets. Padding offsets are added to the
12852     * fading edges to extend the length of the fade so that it covers pixels
12853     * drawn inside the padding.
12854     *
12855     * Subclasses of this class should override this method if they need
12856     * to draw content inside the padding.
12857     *
12858     * @return True if padding offset must be applied, false otherwise.
12859     *
12860     * @see #getLeftPaddingOffset()
12861     * @see #getRightPaddingOffset()
12862     * @see #getTopPaddingOffset()
12863     * @see #getBottomPaddingOffset()
12864     *
12865     * @since CURRENT
12866     */
12867    protected boolean isPaddingOffsetRequired() {
12868        return false;
12869    }
12870
12871    /**
12872     * Amount by which to extend the left fading region. Called only when
12873     * {@link #isPaddingOffsetRequired()} returns true.
12874     *
12875     * @return The left padding offset in pixels.
12876     *
12877     * @see #isPaddingOffsetRequired()
12878     *
12879     * @since CURRENT
12880     */
12881    protected int getLeftPaddingOffset() {
12882        return 0;
12883    }
12884
12885    /**
12886     * Amount by which to extend the right fading region. Called only when
12887     * {@link #isPaddingOffsetRequired()} returns true.
12888     *
12889     * @return The right padding offset in pixels.
12890     *
12891     * @see #isPaddingOffsetRequired()
12892     *
12893     * @since CURRENT
12894     */
12895    protected int getRightPaddingOffset() {
12896        return 0;
12897    }
12898
12899    /**
12900     * Amount by which to extend the top fading region. Called only when
12901     * {@link #isPaddingOffsetRequired()} returns true.
12902     *
12903     * @return The top padding offset in pixels.
12904     *
12905     * @see #isPaddingOffsetRequired()
12906     *
12907     * @since CURRENT
12908     */
12909    protected int getTopPaddingOffset() {
12910        return 0;
12911    }
12912
12913    /**
12914     * Amount by which to extend the bottom fading region. Called only when
12915     * {@link #isPaddingOffsetRequired()} returns true.
12916     *
12917     * @return The bottom padding offset in pixels.
12918     *
12919     * @see #isPaddingOffsetRequired()
12920     *
12921     * @since CURRENT
12922     */
12923    protected int getBottomPaddingOffset() {
12924        return 0;
12925    }
12926
12927    /**
12928     * @hide
12929     * @param offsetRequired
12930     */
12931    protected int getFadeTop(boolean offsetRequired) {
12932        int top = mPaddingTop;
12933        if (offsetRequired) top += getTopPaddingOffset();
12934        return top;
12935    }
12936
12937    /**
12938     * @hide
12939     * @param offsetRequired
12940     */
12941    protected int getFadeHeight(boolean offsetRequired) {
12942        int padding = mPaddingTop;
12943        if (offsetRequired) padding += getTopPaddingOffset();
12944        return mBottom - mTop - mPaddingBottom - padding;
12945    }
12946
12947    /**
12948     * <p>Indicates whether this view is attached to a hardware accelerated
12949     * window or not.</p>
12950     *
12951     * <p>Even if this method returns true, it does not mean that every call
12952     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12953     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12954     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12955     * window is hardware accelerated,
12956     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12957     * return false, and this method will return true.</p>
12958     *
12959     * @return True if the view is attached to a window and the window is
12960     *         hardware accelerated; false in any other case.
12961     */
12962    public boolean isHardwareAccelerated() {
12963        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12964    }
12965
12966    /**
12967     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12968     * case of an active Animation being run on the view.
12969     */
12970    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12971            Animation a, boolean scalingRequired) {
12972        Transformation invalidationTransform;
12973        final int flags = parent.mGroupFlags;
12974        final boolean initialized = a.isInitialized();
12975        if (!initialized) {
12976            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12977            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12978            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
12979            onAnimationStart();
12980        }
12981
12982        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12983        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12984            if (parent.mInvalidationTransformation == null) {
12985                parent.mInvalidationTransformation = new Transformation();
12986            }
12987            invalidationTransform = parent.mInvalidationTransformation;
12988            a.getTransformation(drawingTime, invalidationTransform, 1f);
12989        } else {
12990            invalidationTransform = parent.mChildTransformation;
12991        }
12992
12993        if (more) {
12994            if (!a.willChangeBounds()) {
12995                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
12996                        parent.FLAG_OPTIMIZE_INVALIDATE) {
12997                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
12998                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
12999                    // The child need to draw an animation, potentially offscreen, so
13000                    // make sure we do not cancel invalidate requests
13001                    parent.mPrivateFlags |= DRAW_ANIMATION;
13002                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13003                }
13004            } else {
13005                if (parent.mInvalidateRegion == null) {
13006                    parent.mInvalidateRegion = new RectF();
13007                }
13008                final RectF region = parent.mInvalidateRegion;
13009                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13010                        invalidationTransform);
13011
13012                // The child need to draw an animation, potentially offscreen, so
13013                // make sure we do not cancel invalidate requests
13014                parent.mPrivateFlags |= DRAW_ANIMATION;
13015
13016                final int left = mLeft + (int) region.left;
13017                final int top = mTop + (int) region.top;
13018                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13019                        top + (int) (region.height() + .5f));
13020            }
13021        }
13022        return more;
13023    }
13024
13025    /**
13026     * This method is called by getDisplayList() when a display list is created or re-rendered.
13027     * It sets or resets the current value of all properties on that display list (resetting is
13028     * necessary when a display list is being re-created, because we need to make sure that
13029     * previously-set transform values
13030     */
13031    void setDisplayListProperties(DisplayList displayList) {
13032        if (displayList != null) {
13033            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13034            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13035            if (mParent instanceof ViewGroup) {
13036                displayList.setClipChildren(
13037                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13038            }
13039            float alpha = 1;
13040            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13041                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13042                ViewGroup parentVG = (ViewGroup) mParent;
13043                final boolean hasTransform =
13044                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13045                if (hasTransform) {
13046                    Transformation transform = parentVG.mChildTransformation;
13047                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13048                    if (transformType != Transformation.TYPE_IDENTITY) {
13049                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13050                            alpha = transform.getAlpha();
13051                        }
13052                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13053                            displayList.setStaticMatrix(transform.getMatrix());
13054                        }
13055                    }
13056                }
13057            }
13058            if (mTransformationInfo != null) {
13059                alpha *= mTransformationInfo.mAlpha;
13060                if (alpha < 1) {
13061                    final int multipliedAlpha = (int) (255 * alpha);
13062                    if (onSetAlpha(multipliedAlpha)) {
13063                        alpha = 1;
13064                    }
13065                }
13066                displayList.setTransformationInfo(alpha,
13067                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13068                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13069                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13070                        mTransformationInfo.mScaleY);
13071                if (mTransformationInfo.mCamera == null) {
13072                    mTransformationInfo.mCamera = new Camera();
13073                    mTransformationInfo.matrix3D = new Matrix();
13074                }
13075                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13076                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
13077                    displayList.setPivotX(getPivotX());
13078                    displayList.setPivotY(getPivotY());
13079                }
13080            } else if (alpha < 1) {
13081                displayList.setAlpha(alpha);
13082            }
13083        }
13084    }
13085
13086    /**
13087     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13088     * This draw() method is an implementation detail and is not intended to be overridden or
13089     * to be called from anywhere else other than ViewGroup.drawChild().
13090     */
13091    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13092        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13093        boolean more = false;
13094        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13095        final int flags = parent.mGroupFlags;
13096
13097        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13098            parent.mChildTransformation.clear();
13099            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13100        }
13101
13102        Transformation transformToApply = null;
13103        boolean concatMatrix = false;
13104
13105        boolean scalingRequired = false;
13106        boolean caching;
13107        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
13108
13109        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13110        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13111                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13112            caching = true;
13113            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13114            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13115        } else {
13116            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13117        }
13118
13119        final Animation a = getAnimation();
13120        if (a != null) {
13121            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13122            concatMatrix = a.willChangeTransformationMatrix();
13123            if (concatMatrix) {
13124                mPrivateFlags3 |= VIEW_IS_ANIMATING_TRANSFORM;
13125            }
13126            transformToApply = parent.mChildTransformation;
13127        } else {
13128            if ((mPrivateFlags3 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
13129                    mDisplayList != null) {
13130                // No longer animating: clear out old animation matrix
13131                mDisplayList.setAnimationMatrix(null);
13132                mPrivateFlags3 &= ~VIEW_IS_ANIMATING_TRANSFORM;
13133            }
13134            if (!useDisplayListProperties &&
13135                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13136                final boolean hasTransform =
13137                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13138                if (hasTransform) {
13139                    final int transformType = parent.mChildTransformation.getTransformationType();
13140                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13141                            parent.mChildTransformation : null;
13142                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13143                }
13144            }
13145        }
13146
13147        concatMatrix |= !childHasIdentityMatrix;
13148
13149        // Sets the flag as early as possible to allow draw() implementations
13150        // to call invalidate() successfully when doing animations
13151        mPrivateFlags |= DRAWN;
13152
13153        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13154                (mPrivateFlags & DRAW_ANIMATION) == 0) {
13155            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
13156            return more;
13157        }
13158        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
13159
13160        if (hardwareAccelerated) {
13161            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13162            // retain the flag's value temporarily in the mRecreateDisplayList flag
13163            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
13164            mPrivateFlags &= ~INVALIDATED;
13165        }
13166
13167        computeScroll();
13168
13169        final int sx = mScrollX;
13170        final int sy = mScrollY;
13171
13172        DisplayList displayList = null;
13173        Bitmap cache = null;
13174        boolean hasDisplayList = false;
13175        if (caching) {
13176            if (!hardwareAccelerated) {
13177                if (layerType != LAYER_TYPE_NONE) {
13178                    layerType = LAYER_TYPE_SOFTWARE;
13179                    buildDrawingCache(true);
13180                }
13181                cache = getDrawingCache(true);
13182            } else {
13183                switch (layerType) {
13184                    case LAYER_TYPE_SOFTWARE:
13185                        if (useDisplayListProperties) {
13186                            hasDisplayList = canHaveDisplayList();
13187                        } else {
13188                            buildDrawingCache(true);
13189                            cache = getDrawingCache(true);
13190                        }
13191                        break;
13192                    case LAYER_TYPE_HARDWARE:
13193                        if (useDisplayListProperties) {
13194                            hasDisplayList = canHaveDisplayList();
13195                        }
13196                        break;
13197                    case LAYER_TYPE_NONE:
13198                        // Delay getting the display list until animation-driven alpha values are
13199                        // set up and possibly passed on to the view
13200                        hasDisplayList = canHaveDisplayList();
13201                        break;
13202                }
13203            }
13204        }
13205        useDisplayListProperties &= hasDisplayList;
13206        if (useDisplayListProperties) {
13207            displayList = getDisplayList();
13208            if (!displayList.isValid()) {
13209                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13210                // to getDisplayList(), the display list will be marked invalid and we should not
13211                // try to use it again.
13212                displayList = null;
13213                hasDisplayList = false;
13214                useDisplayListProperties = false;
13215            }
13216        }
13217
13218        final boolean hasNoCache = cache == null || hasDisplayList;
13219        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13220                layerType != LAYER_TYPE_HARDWARE;
13221
13222        int restoreTo = -1;
13223        if (!useDisplayListProperties || transformToApply != null) {
13224            restoreTo = canvas.save();
13225        }
13226        if (offsetForScroll) {
13227            canvas.translate(mLeft - sx, mTop - sy);
13228        } else {
13229            if (!useDisplayListProperties) {
13230                canvas.translate(mLeft, mTop);
13231            }
13232            if (scalingRequired) {
13233                if (useDisplayListProperties) {
13234                    // TODO: Might not need this if we put everything inside the DL
13235                    restoreTo = canvas.save();
13236                }
13237                // mAttachInfo cannot be null, otherwise scalingRequired == false
13238                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13239                canvas.scale(scale, scale);
13240            }
13241        }
13242
13243        float alpha = useDisplayListProperties ? 1 : getAlpha();
13244        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13245                (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
13246            if (transformToApply != null || !childHasIdentityMatrix) {
13247                int transX = 0;
13248                int transY = 0;
13249
13250                if (offsetForScroll) {
13251                    transX = -sx;
13252                    transY = -sy;
13253                }
13254
13255                if (transformToApply != null) {
13256                    if (concatMatrix) {
13257                        if (useDisplayListProperties) {
13258                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13259                        } else {
13260                            // Undo the scroll translation, apply the transformation matrix,
13261                            // then redo the scroll translate to get the correct result.
13262                            canvas.translate(-transX, -transY);
13263                            canvas.concat(transformToApply.getMatrix());
13264                            canvas.translate(transX, transY);
13265                        }
13266                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13267                    }
13268
13269                    float transformAlpha = transformToApply.getAlpha();
13270                    if (transformAlpha < 1) {
13271                        alpha *= transformAlpha;
13272                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13273                    }
13274                }
13275
13276                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13277                    canvas.translate(-transX, -transY);
13278                    canvas.concat(getMatrix());
13279                    canvas.translate(transX, transY);
13280                }
13281            }
13282
13283            // Deal with alpha if it is or used to be <1
13284            if (alpha < 1 ||
13285                    (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
13286                if (alpha < 1) {
13287                    mPrivateFlags3 |= VIEW_IS_ANIMATING_ALPHA;
13288                } else {
13289                    mPrivateFlags3 &= ~VIEW_IS_ANIMATING_ALPHA;
13290                }
13291                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13292                if (hasNoCache) {
13293                    final int multipliedAlpha = (int) (255 * alpha);
13294                    if (!onSetAlpha(multipliedAlpha)) {
13295                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13296                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13297                                layerType != LAYER_TYPE_NONE) {
13298                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13299                        }
13300                        if (useDisplayListProperties) {
13301                            displayList.setAlpha(alpha * getAlpha());
13302                        } else  if (layerType == LAYER_TYPE_NONE) {
13303                            final int scrollX = hasDisplayList ? 0 : sx;
13304                            final int scrollY = hasDisplayList ? 0 : sy;
13305                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13306                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13307                        }
13308                    } else {
13309                        // Alpha is handled by the child directly, clobber the layer's alpha
13310                        mPrivateFlags |= ALPHA_SET;
13311                    }
13312                }
13313            }
13314        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13315            onSetAlpha(255);
13316            mPrivateFlags &= ~ALPHA_SET;
13317        }
13318
13319        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13320                !useDisplayListProperties) {
13321            if (offsetForScroll) {
13322                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13323            } else {
13324                if (!scalingRequired || cache == null) {
13325                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13326                } else {
13327                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13328                }
13329            }
13330        }
13331
13332        if (!useDisplayListProperties && hasDisplayList) {
13333            displayList = getDisplayList();
13334            if (!displayList.isValid()) {
13335                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13336                // to getDisplayList(), the display list will be marked invalid and we should not
13337                // try to use it again.
13338                displayList = null;
13339                hasDisplayList = false;
13340            }
13341        }
13342
13343        if (hasNoCache) {
13344            boolean layerRendered = false;
13345            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13346                final HardwareLayer layer = getHardwareLayer();
13347                if (layer != null && layer.isValid()) {
13348                    mLayerPaint.setAlpha((int) (alpha * 255));
13349                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13350                    layerRendered = true;
13351                } else {
13352                    final int scrollX = hasDisplayList ? 0 : sx;
13353                    final int scrollY = hasDisplayList ? 0 : sy;
13354                    canvas.saveLayer(scrollX, scrollY,
13355                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13356                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13357                }
13358            }
13359
13360            if (!layerRendered) {
13361                if (!hasDisplayList) {
13362                    // Fast path for layouts with no backgrounds
13363                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13364                        mPrivateFlags &= ~DIRTY_MASK;
13365                        dispatchDraw(canvas);
13366                    } else {
13367                        draw(canvas);
13368                    }
13369                } else {
13370                    mPrivateFlags &= ~DIRTY_MASK;
13371                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13372                }
13373            }
13374        } else if (cache != null) {
13375            mPrivateFlags &= ~DIRTY_MASK;
13376            Paint cachePaint;
13377
13378            if (layerType == LAYER_TYPE_NONE) {
13379                cachePaint = parent.mCachePaint;
13380                if (cachePaint == null) {
13381                    cachePaint = new Paint();
13382                    cachePaint.setDither(false);
13383                    parent.mCachePaint = cachePaint;
13384                }
13385                if (alpha < 1) {
13386                    cachePaint.setAlpha((int) (alpha * 255));
13387                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13388                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13389                    cachePaint.setAlpha(255);
13390                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13391                }
13392            } else {
13393                cachePaint = mLayerPaint;
13394                cachePaint.setAlpha((int) (alpha * 255));
13395            }
13396            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13397        }
13398
13399        if (restoreTo >= 0) {
13400            canvas.restoreToCount(restoreTo);
13401        }
13402
13403        if (a != null && !more) {
13404            if (!hardwareAccelerated && !a.getFillAfter()) {
13405                onSetAlpha(255);
13406            }
13407            parent.finishAnimatingView(this, a);
13408        }
13409
13410        if (more && hardwareAccelerated) {
13411            // invalidation is the trigger to recreate display lists, so if we're using
13412            // display lists to render, force an invalidate to allow the animation to
13413            // continue drawing another frame
13414            parent.invalidate(true);
13415            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13416                // alpha animations should cause the child to recreate its display list
13417                invalidate(true);
13418            }
13419        }
13420
13421        mRecreateDisplayList = false;
13422
13423        return more;
13424    }
13425
13426    /**
13427     * Manually render this view (and all of its children) to the given Canvas.
13428     * The view must have already done a full layout before this function is
13429     * called.  When implementing a view, implement
13430     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13431     * If you do need to override this method, call the superclass version.
13432     *
13433     * @param canvas The Canvas to which the View is rendered.
13434     */
13435    public void draw(Canvas canvas) {
13436        final int privateFlags = mPrivateFlags;
13437        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13438                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13439        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13440
13441        /*
13442         * Draw traversal performs several drawing steps which must be executed
13443         * in the appropriate order:
13444         *
13445         *      1. Draw the background
13446         *      2. If necessary, save the canvas' layers to prepare for fading
13447         *      3. Draw view's content
13448         *      4. Draw children
13449         *      5. If necessary, draw the fading edges and restore layers
13450         *      6. Draw decorations (scrollbars for instance)
13451         */
13452
13453        // Step 1, draw the background, if needed
13454        int saveCount;
13455
13456        if (!dirtyOpaque) {
13457            final Drawable background = mBackground;
13458            if (background != null) {
13459                final int scrollX = mScrollX;
13460                final int scrollY = mScrollY;
13461
13462                if (mBackgroundSizeChanged) {
13463                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13464                    mBackgroundSizeChanged = false;
13465                }
13466
13467                if ((scrollX | scrollY) == 0) {
13468                    background.draw(canvas);
13469                } else {
13470                    canvas.translate(scrollX, scrollY);
13471                    background.draw(canvas);
13472                    canvas.translate(-scrollX, -scrollY);
13473                }
13474            }
13475        }
13476
13477        // skip step 2 & 5 if possible (common case)
13478        final int viewFlags = mViewFlags;
13479        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13480        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13481        if (!verticalEdges && !horizontalEdges) {
13482            // Step 3, draw the content
13483            if (!dirtyOpaque) onDraw(canvas);
13484
13485            // Step 4, draw the children
13486            dispatchDraw(canvas);
13487
13488            // Step 6, draw decorations (scrollbars)
13489            onDrawScrollBars(canvas);
13490
13491            // we're done...
13492            return;
13493        }
13494
13495        /*
13496         * Here we do the full fledged routine...
13497         * (this is an uncommon case where speed matters less,
13498         * this is why we repeat some of the tests that have been
13499         * done above)
13500         */
13501
13502        boolean drawTop = false;
13503        boolean drawBottom = false;
13504        boolean drawLeft = false;
13505        boolean drawRight = false;
13506
13507        float topFadeStrength = 0.0f;
13508        float bottomFadeStrength = 0.0f;
13509        float leftFadeStrength = 0.0f;
13510        float rightFadeStrength = 0.0f;
13511
13512        // Step 2, save the canvas' layers
13513        int paddingLeft = mPaddingLeft;
13514
13515        final boolean offsetRequired = isPaddingOffsetRequired();
13516        if (offsetRequired) {
13517            paddingLeft += getLeftPaddingOffset();
13518        }
13519
13520        int left = mScrollX + paddingLeft;
13521        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13522        int top = mScrollY + getFadeTop(offsetRequired);
13523        int bottom = top + getFadeHeight(offsetRequired);
13524
13525        if (offsetRequired) {
13526            right += getRightPaddingOffset();
13527            bottom += getBottomPaddingOffset();
13528        }
13529
13530        final ScrollabilityCache scrollabilityCache = mScrollCache;
13531        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13532        int length = (int) fadeHeight;
13533
13534        // clip the fade length if top and bottom fades overlap
13535        // overlapping fades produce odd-looking artifacts
13536        if (verticalEdges && (top + length > bottom - length)) {
13537            length = (bottom - top) / 2;
13538        }
13539
13540        // also clip horizontal fades if necessary
13541        if (horizontalEdges && (left + length > right - length)) {
13542            length = (right - left) / 2;
13543        }
13544
13545        if (verticalEdges) {
13546            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13547            drawTop = topFadeStrength * fadeHeight > 1.0f;
13548            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13549            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13550        }
13551
13552        if (horizontalEdges) {
13553            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13554            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13555            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13556            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13557        }
13558
13559        saveCount = canvas.getSaveCount();
13560
13561        int solidColor = getSolidColor();
13562        if (solidColor == 0) {
13563            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13564
13565            if (drawTop) {
13566                canvas.saveLayer(left, top, right, top + length, null, flags);
13567            }
13568
13569            if (drawBottom) {
13570                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13571            }
13572
13573            if (drawLeft) {
13574                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13575            }
13576
13577            if (drawRight) {
13578                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13579            }
13580        } else {
13581            scrollabilityCache.setFadeColor(solidColor);
13582        }
13583
13584        // Step 3, draw the content
13585        if (!dirtyOpaque) onDraw(canvas);
13586
13587        // Step 4, draw the children
13588        dispatchDraw(canvas);
13589
13590        // Step 5, draw the fade effect and restore layers
13591        final Paint p = scrollabilityCache.paint;
13592        final Matrix matrix = scrollabilityCache.matrix;
13593        final Shader fade = scrollabilityCache.shader;
13594
13595        if (drawTop) {
13596            matrix.setScale(1, fadeHeight * topFadeStrength);
13597            matrix.postTranslate(left, top);
13598            fade.setLocalMatrix(matrix);
13599            canvas.drawRect(left, top, right, top + length, p);
13600        }
13601
13602        if (drawBottom) {
13603            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13604            matrix.postRotate(180);
13605            matrix.postTranslate(left, bottom);
13606            fade.setLocalMatrix(matrix);
13607            canvas.drawRect(left, bottom - length, right, bottom, p);
13608        }
13609
13610        if (drawLeft) {
13611            matrix.setScale(1, fadeHeight * leftFadeStrength);
13612            matrix.postRotate(-90);
13613            matrix.postTranslate(left, top);
13614            fade.setLocalMatrix(matrix);
13615            canvas.drawRect(left, top, left + length, bottom, p);
13616        }
13617
13618        if (drawRight) {
13619            matrix.setScale(1, fadeHeight * rightFadeStrength);
13620            matrix.postRotate(90);
13621            matrix.postTranslate(right, top);
13622            fade.setLocalMatrix(matrix);
13623            canvas.drawRect(right - length, top, right, bottom, p);
13624        }
13625
13626        canvas.restoreToCount(saveCount);
13627
13628        // Step 6, draw decorations (scrollbars)
13629        onDrawScrollBars(canvas);
13630    }
13631
13632    /**
13633     * Override this if your view is known to always be drawn on top of a solid color background,
13634     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13635     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13636     * should be set to 0xFF.
13637     *
13638     * @see #setVerticalFadingEdgeEnabled(boolean)
13639     * @see #setHorizontalFadingEdgeEnabled(boolean)
13640     *
13641     * @return The known solid color background for this view, or 0 if the color may vary
13642     */
13643    @ViewDebug.ExportedProperty(category = "drawing")
13644    public int getSolidColor() {
13645        return 0;
13646    }
13647
13648    /**
13649     * Build a human readable string representation of the specified view flags.
13650     *
13651     * @param flags the view flags to convert to a string
13652     * @return a String representing the supplied flags
13653     */
13654    private static String printFlags(int flags) {
13655        String output = "";
13656        int numFlags = 0;
13657        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13658            output += "TAKES_FOCUS";
13659            numFlags++;
13660        }
13661
13662        switch (flags & VISIBILITY_MASK) {
13663        case INVISIBLE:
13664            if (numFlags > 0) {
13665                output += " ";
13666            }
13667            output += "INVISIBLE";
13668            // USELESS HERE numFlags++;
13669            break;
13670        case GONE:
13671            if (numFlags > 0) {
13672                output += " ";
13673            }
13674            output += "GONE";
13675            // USELESS HERE numFlags++;
13676            break;
13677        default:
13678            break;
13679        }
13680        return output;
13681    }
13682
13683    /**
13684     * Build a human readable string representation of the specified private
13685     * view flags.
13686     *
13687     * @param privateFlags the private view flags to convert to a string
13688     * @return a String representing the supplied flags
13689     */
13690    private static String printPrivateFlags(int privateFlags) {
13691        String output = "";
13692        int numFlags = 0;
13693
13694        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13695            output += "WANTS_FOCUS";
13696            numFlags++;
13697        }
13698
13699        if ((privateFlags & FOCUSED) == FOCUSED) {
13700            if (numFlags > 0) {
13701                output += " ";
13702            }
13703            output += "FOCUSED";
13704            numFlags++;
13705        }
13706
13707        if ((privateFlags & SELECTED) == SELECTED) {
13708            if (numFlags > 0) {
13709                output += " ";
13710            }
13711            output += "SELECTED";
13712            numFlags++;
13713        }
13714
13715        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13716            if (numFlags > 0) {
13717                output += " ";
13718            }
13719            output += "IS_ROOT_NAMESPACE";
13720            numFlags++;
13721        }
13722
13723        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13724            if (numFlags > 0) {
13725                output += " ";
13726            }
13727            output += "HAS_BOUNDS";
13728            numFlags++;
13729        }
13730
13731        if ((privateFlags & DRAWN) == DRAWN) {
13732            if (numFlags > 0) {
13733                output += " ";
13734            }
13735            output += "DRAWN";
13736            // USELESS HERE numFlags++;
13737        }
13738        return output;
13739    }
13740
13741    /**
13742     * <p>Indicates whether or not this view's layout will be requested during
13743     * the next hierarchy layout pass.</p>
13744     *
13745     * @return true if the layout will be forced during next layout pass
13746     */
13747    public boolean isLayoutRequested() {
13748        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13749    }
13750
13751    /**
13752     * Assign a size and position to a view and all of its
13753     * descendants
13754     *
13755     * <p>This is the second phase of the layout mechanism.
13756     * (The first is measuring). In this phase, each parent calls
13757     * layout on all of its children to position them.
13758     * This is typically done using the child measurements
13759     * that were stored in the measure pass().</p>
13760     *
13761     * <p>Derived classes should not override this method.
13762     * Derived classes with children should override
13763     * onLayout. In that method, they should
13764     * call layout on each of their children.</p>
13765     *
13766     * @param l Left position, relative to parent
13767     * @param t Top position, relative to parent
13768     * @param r Right position, relative to parent
13769     * @param b Bottom position, relative to parent
13770     */
13771    @SuppressWarnings({"unchecked"})
13772    public void layout(int l, int t, int r, int b) {
13773        int oldL = mLeft;
13774        int oldT = mTop;
13775        int oldB = mBottom;
13776        int oldR = mRight;
13777        boolean changed = setFrame(l, t, r, b);
13778        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13779            onLayout(changed, l, t, r, b);
13780            mPrivateFlags &= ~LAYOUT_REQUIRED;
13781
13782            ListenerInfo li = mListenerInfo;
13783            if (li != null && li.mOnLayoutChangeListeners != null) {
13784                ArrayList<OnLayoutChangeListener> listenersCopy =
13785                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13786                int numListeners = listenersCopy.size();
13787                for (int i = 0; i < numListeners; ++i) {
13788                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13789                }
13790            }
13791        }
13792        mPrivateFlags &= ~FORCE_LAYOUT;
13793    }
13794
13795    /**
13796     * Called from layout when this view should
13797     * assign a size and position to each of its children.
13798     *
13799     * Derived classes with children should override
13800     * this method and call layout on each of
13801     * their children.
13802     * @param changed This is a new size or position for this view
13803     * @param left Left position, relative to parent
13804     * @param top Top position, relative to parent
13805     * @param right Right position, relative to parent
13806     * @param bottom Bottom position, relative to parent
13807     */
13808    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13809    }
13810
13811    /**
13812     * Assign a size and position to this view.
13813     *
13814     * This is called from layout.
13815     *
13816     * @param left Left position, relative to parent
13817     * @param top Top position, relative to parent
13818     * @param right Right position, relative to parent
13819     * @param bottom Bottom position, relative to parent
13820     * @return true if the new size and position are different than the
13821     *         previous ones
13822     * {@hide}
13823     */
13824    protected boolean setFrame(int left, int top, int right, int bottom) {
13825        boolean changed = false;
13826
13827        if (DBG) {
13828            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13829                    + right + "," + bottom + ")");
13830        }
13831
13832        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13833            changed = true;
13834
13835            // Remember our drawn bit
13836            int drawn = mPrivateFlags & DRAWN;
13837
13838            int oldWidth = mRight - mLeft;
13839            int oldHeight = mBottom - mTop;
13840            int newWidth = right - left;
13841            int newHeight = bottom - top;
13842            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13843
13844            // Invalidate our old position
13845            invalidate(sizeChanged);
13846
13847            mLeft = left;
13848            mTop = top;
13849            mRight = right;
13850            mBottom = bottom;
13851            if (mDisplayList != null) {
13852                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13853            }
13854
13855            mPrivateFlags |= HAS_BOUNDS;
13856
13857
13858            if (sizeChanged) {
13859                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13860                    // A change in dimension means an auto-centered pivot point changes, too
13861                    if (mTransformationInfo != null) {
13862                        mTransformationInfo.mMatrixDirty = true;
13863                    }
13864                }
13865                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13866            }
13867
13868            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13869                // If we are visible, force the DRAWN bit to on so that
13870                // this invalidate will go through (at least to our parent).
13871                // This is because someone may have invalidated this view
13872                // before this call to setFrame came in, thereby clearing
13873                // the DRAWN bit.
13874                mPrivateFlags |= DRAWN;
13875                invalidate(sizeChanged);
13876                // parent display list may need to be recreated based on a change in the bounds
13877                // of any child
13878                invalidateParentCaches();
13879            }
13880
13881            // Reset drawn bit to original value (invalidate turns it off)
13882            mPrivateFlags |= drawn;
13883
13884            mBackgroundSizeChanged = true;
13885        }
13886        return changed;
13887    }
13888
13889    /**
13890     * Finalize inflating a view from XML.  This is called as the last phase
13891     * of inflation, after all child views have been added.
13892     *
13893     * <p>Even if the subclass overrides onFinishInflate, they should always be
13894     * sure to call the super method, so that we get called.
13895     */
13896    protected void onFinishInflate() {
13897    }
13898
13899    /**
13900     * Returns the resources associated with this view.
13901     *
13902     * @return Resources object.
13903     */
13904    public Resources getResources() {
13905        return mResources;
13906    }
13907
13908    /**
13909     * Invalidates the specified Drawable.
13910     *
13911     * @param drawable the drawable to invalidate
13912     */
13913    public void invalidateDrawable(Drawable drawable) {
13914        if (verifyDrawable(drawable)) {
13915            final Rect dirty = drawable.getBounds();
13916            final int scrollX = mScrollX;
13917            final int scrollY = mScrollY;
13918
13919            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13920                    dirty.right + scrollX, dirty.bottom + scrollY);
13921        }
13922    }
13923
13924    /**
13925     * Schedules an action on a drawable to occur at a specified time.
13926     *
13927     * @param who the recipient of the action
13928     * @param what the action to run on the drawable
13929     * @param when the time at which the action must occur. Uses the
13930     *        {@link SystemClock#uptimeMillis} timebase.
13931     */
13932    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13933        if (verifyDrawable(who) && what != null) {
13934            final long delay = when - SystemClock.uptimeMillis();
13935            if (mAttachInfo != null) {
13936                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13937                        Choreographer.CALLBACK_ANIMATION, what, who,
13938                        Choreographer.subtractFrameDelay(delay));
13939            } else {
13940                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13941            }
13942        }
13943    }
13944
13945    /**
13946     * Cancels a scheduled action on a drawable.
13947     *
13948     * @param who the recipient of the action
13949     * @param what the action to cancel
13950     */
13951    public void unscheduleDrawable(Drawable who, Runnable what) {
13952        if (verifyDrawable(who) && what != null) {
13953            if (mAttachInfo != null) {
13954                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13955                        Choreographer.CALLBACK_ANIMATION, what, who);
13956            } else {
13957                ViewRootImpl.getRunQueue().removeCallbacks(what);
13958            }
13959        }
13960    }
13961
13962    /**
13963     * Unschedule any events associated with the given Drawable.  This can be
13964     * used when selecting a new Drawable into a view, so that the previous
13965     * one is completely unscheduled.
13966     *
13967     * @param who The Drawable to unschedule.
13968     *
13969     * @see #drawableStateChanged
13970     */
13971    public void unscheduleDrawable(Drawable who) {
13972        if (mAttachInfo != null && who != null) {
13973            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13974                    Choreographer.CALLBACK_ANIMATION, null, who);
13975        }
13976    }
13977
13978    /**
13979    * Return the layout direction of a given Drawable.
13980    *
13981    * @param who the Drawable to query
13982    * @hide
13983    */
13984    public int getResolvedLayoutDirection(Drawable who) {
13985        return (who == mBackground) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
13986    }
13987
13988    /**
13989     * If your view subclass is displaying its own Drawable objects, it should
13990     * override this function and return true for any Drawable it is
13991     * displaying.  This allows animations for those drawables to be
13992     * scheduled.
13993     *
13994     * <p>Be sure to call through to the super class when overriding this
13995     * function.
13996     *
13997     * @param who The Drawable to verify.  Return true if it is one you are
13998     *            displaying, else return the result of calling through to the
13999     *            super class.
14000     *
14001     * @return boolean If true than the Drawable is being displayed in the
14002     *         view; else false and it is not allowed to animate.
14003     *
14004     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14005     * @see #drawableStateChanged()
14006     */
14007    protected boolean verifyDrawable(Drawable who) {
14008        return who == mBackground;
14009    }
14010
14011    /**
14012     * This function is called whenever the state of the view changes in such
14013     * a way that it impacts the state of drawables being shown.
14014     *
14015     * <p>Be sure to call through to the superclass when overriding this
14016     * function.
14017     *
14018     * @see Drawable#setState(int[])
14019     */
14020    protected void drawableStateChanged() {
14021        Drawable d = mBackground;
14022        if (d != null && d.isStateful()) {
14023            d.setState(getDrawableState());
14024        }
14025    }
14026
14027    /**
14028     * Call this to force a view to update its drawable state. This will cause
14029     * drawableStateChanged to be called on this view. Views that are interested
14030     * in the new state should call getDrawableState.
14031     *
14032     * @see #drawableStateChanged
14033     * @see #getDrawableState
14034     */
14035    public void refreshDrawableState() {
14036        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
14037        drawableStateChanged();
14038
14039        ViewParent parent = mParent;
14040        if (parent != null) {
14041            parent.childDrawableStateChanged(this);
14042        }
14043    }
14044
14045    /**
14046     * Return an array of resource IDs of the drawable states representing the
14047     * current state of the view.
14048     *
14049     * @return The current drawable state
14050     *
14051     * @see Drawable#setState(int[])
14052     * @see #drawableStateChanged()
14053     * @see #onCreateDrawableState(int)
14054     */
14055    public final int[] getDrawableState() {
14056        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
14057            return mDrawableState;
14058        } else {
14059            mDrawableState = onCreateDrawableState(0);
14060            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
14061            return mDrawableState;
14062        }
14063    }
14064
14065    /**
14066     * Generate the new {@link android.graphics.drawable.Drawable} state for
14067     * this view. This is called by the view
14068     * system when the cached Drawable state is determined to be invalid.  To
14069     * retrieve the current state, you should use {@link #getDrawableState}.
14070     *
14071     * @param extraSpace if non-zero, this is the number of extra entries you
14072     * would like in the returned array in which you can place your own
14073     * states.
14074     *
14075     * @return Returns an array holding the current {@link Drawable} state of
14076     * the view.
14077     *
14078     * @see #mergeDrawableStates(int[], int[])
14079     */
14080    protected int[] onCreateDrawableState(int extraSpace) {
14081        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14082                mParent instanceof View) {
14083            return ((View) mParent).onCreateDrawableState(extraSpace);
14084        }
14085
14086        int[] drawableState;
14087
14088        int privateFlags = mPrivateFlags;
14089
14090        int viewStateIndex = 0;
14091        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14092        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14093        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14094        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14095        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14096        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14097        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14098                HardwareRenderer.isAvailable()) {
14099            // This is set if HW acceleration is requested, even if the current
14100            // process doesn't allow it.  This is just to allow app preview
14101            // windows to better match their app.
14102            viewStateIndex |= VIEW_STATE_ACCELERATED;
14103        }
14104        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14105
14106        final int privateFlags2 = mPrivateFlags2;
14107        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14108        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14109
14110        drawableState = VIEW_STATE_SETS[viewStateIndex];
14111
14112        //noinspection ConstantIfStatement
14113        if (false) {
14114            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14115            Log.i("View", toString()
14116                    + " pressed=" + ((privateFlags & PRESSED) != 0)
14117                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14118                    + " fo=" + hasFocus()
14119                    + " sl=" + ((privateFlags & SELECTED) != 0)
14120                    + " wf=" + hasWindowFocus()
14121                    + ": " + Arrays.toString(drawableState));
14122        }
14123
14124        if (extraSpace == 0) {
14125            return drawableState;
14126        }
14127
14128        final int[] fullState;
14129        if (drawableState != null) {
14130            fullState = new int[drawableState.length + extraSpace];
14131            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14132        } else {
14133            fullState = new int[extraSpace];
14134        }
14135
14136        return fullState;
14137    }
14138
14139    /**
14140     * Merge your own state values in <var>additionalState</var> into the base
14141     * state values <var>baseState</var> that were returned by
14142     * {@link #onCreateDrawableState(int)}.
14143     *
14144     * @param baseState The base state values returned by
14145     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14146     * own additional state values.
14147     *
14148     * @param additionalState The additional state values you would like
14149     * added to <var>baseState</var>; this array is not modified.
14150     *
14151     * @return As a convenience, the <var>baseState</var> array you originally
14152     * passed into the function is returned.
14153     *
14154     * @see #onCreateDrawableState(int)
14155     */
14156    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14157        final int N = baseState.length;
14158        int i = N - 1;
14159        while (i >= 0 && baseState[i] == 0) {
14160            i--;
14161        }
14162        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14163        return baseState;
14164    }
14165
14166    /**
14167     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14168     * on all Drawable objects associated with this view.
14169     */
14170    public void jumpDrawablesToCurrentState() {
14171        if (mBackground != null) {
14172            mBackground.jumpToCurrentState();
14173        }
14174    }
14175
14176    /**
14177     * Sets the background color for this view.
14178     * @param color the color of the background
14179     */
14180    @RemotableViewMethod
14181    public void setBackgroundColor(int color) {
14182        if (mBackground instanceof ColorDrawable) {
14183            ((ColorDrawable) mBackground).setColor(color);
14184        } else {
14185            setBackground(new ColorDrawable(color));
14186        }
14187    }
14188
14189    /**
14190     * Set the background to a given resource. The resource should refer to
14191     * a Drawable object or 0 to remove the background.
14192     * @param resid The identifier of the resource.
14193     *
14194     * @attr ref android.R.styleable#View_background
14195     */
14196    @RemotableViewMethod
14197    public void setBackgroundResource(int resid) {
14198        if (resid != 0 && resid == mBackgroundResource) {
14199            return;
14200        }
14201
14202        Drawable d= null;
14203        if (resid != 0) {
14204            d = mResources.getDrawable(resid);
14205        }
14206        setBackground(d);
14207
14208        mBackgroundResource = resid;
14209    }
14210
14211    /**
14212     * Set the background to a given Drawable, or remove the background. If the
14213     * background has padding, this View's padding is set to the background's
14214     * padding. However, when a background is removed, this View's padding isn't
14215     * touched. If setting the padding is desired, please use
14216     * {@link #setPadding(int, int, int, int)}.
14217     *
14218     * @param background The Drawable to use as the background, or null to remove the
14219     *        background
14220     */
14221    public void setBackground(Drawable background) {
14222        //noinspection deprecation
14223        setBackgroundDrawable(background);
14224    }
14225
14226    /**
14227     * @deprecated use {@link #setBackground(Drawable)} instead
14228     */
14229    @Deprecated
14230    public void setBackgroundDrawable(Drawable background) {
14231        if (background == mBackground) {
14232            return;
14233        }
14234
14235        boolean requestLayout = false;
14236
14237        mBackgroundResource = 0;
14238
14239        /*
14240         * Regardless of whether we're setting a new background or not, we want
14241         * to clear the previous drawable.
14242         */
14243        if (mBackground != null) {
14244            mBackground.setCallback(null);
14245            unscheduleDrawable(mBackground);
14246        }
14247
14248        if (background != null) {
14249            Rect padding = sThreadLocal.get();
14250            if (padding == null) {
14251                padding = new Rect();
14252                sThreadLocal.set(padding);
14253            }
14254            if (background.getPadding(padding)) {
14255                switch (background.getResolvedLayoutDirectionSelf()) {
14256                    case LAYOUT_DIRECTION_RTL:
14257                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
14258                        break;
14259                    case LAYOUT_DIRECTION_LTR:
14260                    default:
14261                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
14262                }
14263            }
14264
14265            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14266            // if it has a different minimum size, we should layout again
14267            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14268                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14269                requestLayout = true;
14270            }
14271
14272            background.setCallback(this);
14273            if (background.isStateful()) {
14274                background.setState(getDrawableState());
14275            }
14276            background.setVisible(getVisibility() == VISIBLE, false);
14277            mBackground = background;
14278
14279            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14280                mPrivateFlags &= ~SKIP_DRAW;
14281                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14282                requestLayout = true;
14283            }
14284        } else {
14285            /* Remove the background */
14286            mBackground = null;
14287
14288            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14289                /*
14290                 * This view ONLY drew the background before and we're removing
14291                 * the background, so now it won't draw anything
14292                 * (hence we SKIP_DRAW)
14293                 */
14294                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14295                mPrivateFlags |= SKIP_DRAW;
14296            }
14297
14298            /*
14299             * When the background is set, we try to apply its padding to this
14300             * View. When the background is removed, we don't touch this View's
14301             * padding. This is noted in the Javadocs. Hence, we don't need to
14302             * requestLayout(), the invalidate() below is sufficient.
14303             */
14304
14305            // The old background's minimum size could have affected this
14306            // View's layout, so let's requestLayout
14307            requestLayout = true;
14308        }
14309
14310        computeOpaqueFlags();
14311
14312        if (requestLayout) {
14313            requestLayout();
14314        }
14315
14316        mBackgroundSizeChanged = true;
14317        invalidate(true);
14318    }
14319
14320    /**
14321     * Gets the background drawable
14322     *
14323     * @return The drawable used as the background for this view, if any.
14324     *
14325     * @see #setBackground(Drawable)
14326     *
14327     * @attr ref android.R.styleable#View_background
14328     */
14329    public Drawable getBackground() {
14330        return mBackground;
14331    }
14332
14333    /**
14334     * Sets the padding. The view may add on the space required to display
14335     * the scrollbars, depending on the style and visibility of the scrollbars.
14336     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14337     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14338     * from the values set in this call.
14339     *
14340     * @attr ref android.R.styleable#View_padding
14341     * @attr ref android.R.styleable#View_paddingBottom
14342     * @attr ref android.R.styleable#View_paddingLeft
14343     * @attr ref android.R.styleable#View_paddingRight
14344     * @attr ref android.R.styleable#View_paddingTop
14345     * @param left the left padding in pixels
14346     * @param top the top padding in pixels
14347     * @param right the right padding in pixels
14348     * @param bottom the bottom padding in pixels
14349     */
14350    public void setPadding(int left, int top, int right, int bottom) {
14351        mUserPaddingStart = -1;
14352        mUserPaddingEnd = -1;
14353        mUserPaddingRelative = false;
14354
14355        internalSetPadding(left, top, right, bottom);
14356    }
14357
14358    private void internalSetPadding(int left, int top, int right, int bottom) {
14359        mUserPaddingLeft = left;
14360        mUserPaddingRight = right;
14361        mUserPaddingBottom = bottom;
14362
14363        final int viewFlags = mViewFlags;
14364        boolean changed = false;
14365
14366        // Common case is there are no scroll bars.
14367        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14368            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14369                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14370                        ? 0 : getVerticalScrollbarWidth();
14371                switch (mVerticalScrollbarPosition) {
14372                    case SCROLLBAR_POSITION_DEFAULT:
14373                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
14374                            left += offset;
14375                        } else {
14376                            right += offset;
14377                        }
14378                        break;
14379                    case SCROLLBAR_POSITION_RIGHT:
14380                        right += offset;
14381                        break;
14382                    case SCROLLBAR_POSITION_LEFT:
14383                        left += offset;
14384                        break;
14385                }
14386            }
14387            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14388                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14389                        ? 0 : getHorizontalScrollbarHeight();
14390            }
14391        }
14392
14393        if (mPaddingLeft != left) {
14394            changed = true;
14395            mPaddingLeft = left;
14396        }
14397        if (mPaddingTop != top) {
14398            changed = true;
14399            mPaddingTop = top;
14400        }
14401        if (mPaddingRight != right) {
14402            changed = true;
14403            mPaddingRight = right;
14404        }
14405        if (mPaddingBottom != bottom) {
14406            changed = true;
14407            mPaddingBottom = bottom;
14408        }
14409
14410        if (changed) {
14411            requestLayout();
14412        }
14413    }
14414
14415    /**
14416     * Sets the relative padding. The view may add on the space required to display
14417     * the scrollbars, depending on the style and visibility of the scrollbars.
14418     * from the values set in this call.
14419     *
14420     * @param start the start padding in pixels
14421     * @param top the top padding in pixels
14422     * @param end the end padding in pixels
14423     * @param bottom the bottom padding in pixels
14424     * @hide
14425     */
14426    public void setPaddingRelative(int start, int top, int end, int bottom) {
14427        mUserPaddingStart = start;
14428        mUserPaddingEnd = end;
14429        mUserPaddingRelative = true;
14430
14431        switch(getResolvedLayoutDirection()) {
14432            case LAYOUT_DIRECTION_RTL:
14433                internalSetPadding(end, top, start, bottom);
14434                break;
14435            case LAYOUT_DIRECTION_LTR:
14436            default:
14437                internalSetPadding(start, top, end, bottom);
14438        }
14439    }
14440
14441    /**
14442     * Returns the top padding of this view.
14443     *
14444     * @return the top padding in pixels
14445     */
14446    public int getPaddingTop() {
14447        return mPaddingTop;
14448    }
14449
14450    /**
14451     * Returns the bottom padding of this view. If there are inset and enabled
14452     * scrollbars, this value may include the space required to display the
14453     * scrollbars as well.
14454     *
14455     * @return the bottom padding in pixels
14456     */
14457    public int getPaddingBottom() {
14458        return mPaddingBottom;
14459    }
14460
14461    /**
14462     * Returns the left padding of this view. If there are inset and enabled
14463     * scrollbars, this value may include the space required to display the
14464     * scrollbars as well.
14465     *
14466     * @return the left padding in pixels
14467     */
14468    public int getPaddingLeft() {
14469        return mPaddingLeft;
14470    }
14471
14472    /**
14473     * Returns the start padding of this view depending on its resolved layout direction.
14474     * If there are inset and enabled scrollbars, this value may include the space
14475     * required to display the scrollbars as well.
14476     *
14477     * @return the start padding in pixels
14478     * @hide
14479     */
14480    public int getPaddingStart() {
14481        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14482                mPaddingRight : mPaddingLeft;
14483    }
14484
14485    /**
14486     * Returns the right padding of this view. If there are inset and enabled
14487     * scrollbars, this value may include the space required to display the
14488     * scrollbars as well.
14489     *
14490     * @return the right padding in pixels
14491     */
14492    public int getPaddingRight() {
14493        return mPaddingRight;
14494    }
14495
14496    /**
14497     * Returns the end padding of this view depending on its resolved layout direction.
14498     * If there are inset and enabled scrollbars, this value may include the space
14499     * required to display the scrollbars as well.
14500     *
14501     * @return the end padding in pixels
14502     * @hide
14503     */
14504    public int getPaddingEnd() {
14505        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14506                mPaddingLeft : mPaddingRight;
14507    }
14508
14509    /**
14510     * Return if the padding as been set thru relative values
14511     * {@link #setPaddingRelative(int, int, int, int)}
14512     *
14513     * @return true if the padding is relative or false if it is not.
14514     * @hide
14515     */
14516    public boolean isPaddingRelative() {
14517        return mUserPaddingRelative;
14518    }
14519
14520    /**
14521     * @hide
14522     */
14523    public Insets getOpticalInsets() {
14524        if (mLayoutInsets == null) {
14525            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14526        }
14527        return mLayoutInsets;
14528    }
14529
14530    /**
14531     * @hide
14532     */
14533    public void setLayoutInsets(Insets layoutInsets) {
14534        mLayoutInsets = layoutInsets;
14535    }
14536
14537    /**
14538     * Changes the selection state of this view. A view can be selected or not.
14539     * Note that selection is not the same as focus. Views are typically
14540     * selected in the context of an AdapterView like ListView or GridView;
14541     * the selected view is the view that is highlighted.
14542     *
14543     * @param selected true if the view must be selected, false otherwise
14544     */
14545    public void setSelected(boolean selected) {
14546        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14547            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14548            if (!selected) resetPressedState();
14549            invalidate(true);
14550            refreshDrawableState();
14551            dispatchSetSelected(selected);
14552            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14553                notifyAccessibilityStateChanged();
14554            }
14555        }
14556    }
14557
14558    /**
14559     * Dispatch setSelected to all of this View's children.
14560     *
14561     * @see #setSelected(boolean)
14562     *
14563     * @param selected The new selected state
14564     */
14565    protected void dispatchSetSelected(boolean selected) {
14566    }
14567
14568    /**
14569     * Indicates the selection state of this view.
14570     *
14571     * @return true if the view is selected, false otherwise
14572     */
14573    @ViewDebug.ExportedProperty
14574    public boolean isSelected() {
14575        return (mPrivateFlags & SELECTED) != 0;
14576    }
14577
14578    /**
14579     * Changes the activated state of this view. A view can be activated or not.
14580     * Note that activation is not the same as selection.  Selection is
14581     * a transient property, representing the view (hierarchy) the user is
14582     * currently interacting with.  Activation is a longer-term state that the
14583     * user can move views in and out of.  For example, in a list view with
14584     * single or multiple selection enabled, the views in the current selection
14585     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14586     * here.)  The activated state is propagated down to children of the view it
14587     * is set on.
14588     *
14589     * @param activated true if the view must be activated, false otherwise
14590     */
14591    public void setActivated(boolean activated) {
14592        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14593            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14594            invalidate(true);
14595            refreshDrawableState();
14596            dispatchSetActivated(activated);
14597        }
14598    }
14599
14600    /**
14601     * Dispatch setActivated to all of this View's children.
14602     *
14603     * @see #setActivated(boolean)
14604     *
14605     * @param activated The new activated state
14606     */
14607    protected void dispatchSetActivated(boolean activated) {
14608    }
14609
14610    /**
14611     * Indicates the activation state of this view.
14612     *
14613     * @return true if the view is activated, false otherwise
14614     */
14615    @ViewDebug.ExportedProperty
14616    public boolean isActivated() {
14617        return (mPrivateFlags & ACTIVATED) != 0;
14618    }
14619
14620    /**
14621     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14622     * observer can be used to get notifications when global events, like
14623     * layout, happen.
14624     *
14625     * The returned ViewTreeObserver observer is not guaranteed to remain
14626     * valid for the lifetime of this View. If the caller of this method keeps
14627     * a long-lived reference to ViewTreeObserver, it should always check for
14628     * the return value of {@link ViewTreeObserver#isAlive()}.
14629     *
14630     * @return The ViewTreeObserver for this view's hierarchy.
14631     */
14632    public ViewTreeObserver getViewTreeObserver() {
14633        if (mAttachInfo != null) {
14634            return mAttachInfo.mTreeObserver;
14635        }
14636        if (mFloatingTreeObserver == null) {
14637            mFloatingTreeObserver = new ViewTreeObserver();
14638        }
14639        return mFloatingTreeObserver;
14640    }
14641
14642    /**
14643     * <p>Finds the topmost view in the current view hierarchy.</p>
14644     *
14645     * @return the topmost view containing this view
14646     */
14647    public View getRootView() {
14648        if (mAttachInfo != null) {
14649            final View v = mAttachInfo.mRootView;
14650            if (v != null) {
14651                return v;
14652            }
14653        }
14654
14655        View parent = this;
14656
14657        while (parent.mParent != null && parent.mParent instanceof View) {
14658            parent = (View) parent.mParent;
14659        }
14660
14661        return parent;
14662    }
14663
14664    /**
14665     * <p>Computes the coordinates of this view on the screen. The argument
14666     * must be an array of two integers. After the method returns, the array
14667     * contains the x and y location in that order.</p>
14668     *
14669     * @param location an array of two integers in which to hold the coordinates
14670     */
14671    public void getLocationOnScreen(int[] location) {
14672        getLocationInWindow(location);
14673
14674        final AttachInfo info = mAttachInfo;
14675        if (info != null) {
14676            location[0] += info.mWindowLeft;
14677            location[1] += info.mWindowTop;
14678        }
14679    }
14680
14681    /**
14682     * <p>Computes the coordinates of this view in its window. The argument
14683     * must be an array of two integers. After the method returns, the array
14684     * contains the x and y location in that order.</p>
14685     *
14686     * @param location an array of two integers in which to hold the coordinates
14687     */
14688    public void getLocationInWindow(int[] location) {
14689        if (location == null || location.length < 2) {
14690            throw new IllegalArgumentException("location must be an array of two integers");
14691        }
14692
14693        if (mAttachInfo == null) {
14694            // When the view is not attached to a window, this method does not make sense
14695            location[0] = location[1] = 0;
14696            return;
14697        }
14698
14699        float[] position = mAttachInfo.mTmpTransformLocation;
14700        position[0] = position[1] = 0.0f;
14701
14702        if (!hasIdentityMatrix()) {
14703            getMatrix().mapPoints(position);
14704        }
14705
14706        position[0] += mLeft;
14707        position[1] += mTop;
14708
14709        ViewParent viewParent = mParent;
14710        while (viewParent instanceof View) {
14711            final View view = (View) viewParent;
14712
14713            position[0] -= view.mScrollX;
14714            position[1] -= view.mScrollY;
14715
14716            if (!view.hasIdentityMatrix()) {
14717                view.getMatrix().mapPoints(position);
14718            }
14719
14720            position[0] += view.mLeft;
14721            position[1] += view.mTop;
14722
14723            viewParent = view.mParent;
14724         }
14725
14726        if (viewParent instanceof ViewRootImpl) {
14727            // *cough*
14728            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14729            position[1] -= vr.mCurScrollY;
14730        }
14731
14732        location[0] = (int) (position[0] + 0.5f);
14733        location[1] = (int) (position[1] + 0.5f);
14734    }
14735
14736    /**
14737     * {@hide}
14738     * @param id the id of the view to be found
14739     * @return the view of the specified id, null if cannot be found
14740     */
14741    protected View findViewTraversal(int id) {
14742        if (id == mID) {
14743            return this;
14744        }
14745        return null;
14746    }
14747
14748    /**
14749     * {@hide}
14750     * @param tag the tag of the view to be found
14751     * @return the view of specified tag, null if cannot be found
14752     */
14753    protected View findViewWithTagTraversal(Object tag) {
14754        if (tag != null && tag.equals(mTag)) {
14755            return this;
14756        }
14757        return null;
14758    }
14759
14760    /**
14761     * {@hide}
14762     * @param predicate The predicate to evaluate.
14763     * @param childToSkip If not null, ignores this child during the recursive traversal.
14764     * @return The first view that matches the predicate or null.
14765     */
14766    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14767        if (predicate.apply(this)) {
14768            return this;
14769        }
14770        return null;
14771    }
14772
14773    /**
14774     * Look for a child view with the given id.  If this view has the given
14775     * id, return this view.
14776     *
14777     * @param id The id to search for.
14778     * @return The view that has the given id in the hierarchy or null
14779     */
14780    public final View findViewById(int id) {
14781        if (id < 0) {
14782            return null;
14783        }
14784        return findViewTraversal(id);
14785    }
14786
14787    /**
14788     * Finds a view by its unuque and stable accessibility id.
14789     *
14790     * @param accessibilityId The searched accessibility id.
14791     * @return The found view.
14792     */
14793    final View findViewByAccessibilityId(int accessibilityId) {
14794        if (accessibilityId < 0) {
14795            return null;
14796        }
14797        return findViewByAccessibilityIdTraversal(accessibilityId);
14798    }
14799
14800    /**
14801     * Performs the traversal to find a view by its unuque and stable accessibility id.
14802     *
14803     * <strong>Note:</strong>This method does not stop at the root namespace
14804     * boundary since the user can touch the screen at an arbitrary location
14805     * potentially crossing the root namespace bounday which will send an
14806     * accessibility event to accessibility services and they should be able
14807     * to obtain the event source. Also accessibility ids are guaranteed to be
14808     * unique in the window.
14809     *
14810     * @param accessibilityId The accessibility id.
14811     * @return The found view.
14812     */
14813    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14814        if (getAccessibilityViewId() == accessibilityId) {
14815            return this;
14816        }
14817        return null;
14818    }
14819
14820    /**
14821     * Look for a child view with the given tag.  If this view has the given
14822     * tag, return this view.
14823     *
14824     * @param tag The tag to search for, using "tag.equals(getTag())".
14825     * @return The View that has the given tag in the hierarchy or null
14826     */
14827    public final View findViewWithTag(Object tag) {
14828        if (tag == null) {
14829            return null;
14830        }
14831        return findViewWithTagTraversal(tag);
14832    }
14833
14834    /**
14835     * {@hide}
14836     * Look for a child view that matches the specified predicate.
14837     * If this view matches the predicate, return this view.
14838     *
14839     * @param predicate The predicate to evaluate.
14840     * @return The first view that matches the predicate or null.
14841     */
14842    public final View findViewByPredicate(Predicate<View> predicate) {
14843        return findViewByPredicateTraversal(predicate, null);
14844    }
14845
14846    /**
14847     * {@hide}
14848     * Look for a child view that matches the specified predicate,
14849     * starting with the specified view and its descendents and then
14850     * recusively searching the ancestors and siblings of that view
14851     * until this view is reached.
14852     *
14853     * This method is useful in cases where the predicate does not match
14854     * a single unique view (perhaps multiple views use the same id)
14855     * and we are trying to find the view that is "closest" in scope to the
14856     * starting view.
14857     *
14858     * @param start The view to start from.
14859     * @param predicate The predicate to evaluate.
14860     * @return The first view that matches the predicate or null.
14861     */
14862    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14863        View childToSkip = null;
14864        for (;;) {
14865            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14866            if (view != null || start == this) {
14867                return view;
14868            }
14869
14870            ViewParent parent = start.getParent();
14871            if (parent == null || !(parent instanceof View)) {
14872                return null;
14873            }
14874
14875            childToSkip = start;
14876            start = (View) parent;
14877        }
14878    }
14879
14880    /**
14881     * Sets the identifier for this view. The identifier does not have to be
14882     * unique in this view's hierarchy. The identifier should be a positive
14883     * number.
14884     *
14885     * @see #NO_ID
14886     * @see #getId()
14887     * @see #findViewById(int)
14888     *
14889     * @param id a number used to identify the view
14890     *
14891     * @attr ref android.R.styleable#View_id
14892     */
14893    public void setId(int id) {
14894        mID = id;
14895    }
14896
14897    /**
14898     * {@hide}
14899     *
14900     * @param isRoot true if the view belongs to the root namespace, false
14901     *        otherwise
14902     */
14903    public void setIsRootNamespace(boolean isRoot) {
14904        if (isRoot) {
14905            mPrivateFlags |= IS_ROOT_NAMESPACE;
14906        } else {
14907            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14908        }
14909    }
14910
14911    /**
14912     * {@hide}
14913     *
14914     * @return true if the view belongs to the root namespace, false otherwise
14915     */
14916    public boolean isRootNamespace() {
14917        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14918    }
14919
14920    /**
14921     * Returns this view's identifier.
14922     *
14923     * @return a positive integer used to identify the view or {@link #NO_ID}
14924     *         if the view has no ID
14925     *
14926     * @see #setId(int)
14927     * @see #findViewById(int)
14928     * @attr ref android.R.styleable#View_id
14929     */
14930    @ViewDebug.CapturedViewProperty
14931    public int getId() {
14932        return mID;
14933    }
14934
14935    /**
14936     * Returns this view's tag.
14937     *
14938     * @return the Object stored in this view as a tag
14939     *
14940     * @see #setTag(Object)
14941     * @see #getTag(int)
14942     */
14943    @ViewDebug.ExportedProperty
14944    public Object getTag() {
14945        return mTag;
14946    }
14947
14948    /**
14949     * Sets the tag associated with this view. A tag can be used to mark
14950     * a view in its hierarchy and does not have to be unique within the
14951     * hierarchy. Tags can also be used to store data within a view without
14952     * resorting to another data structure.
14953     *
14954     * @param tag an Object to tag the view with
14955     *
14956     * @see #getTag()
14957     * @see #setTag(int, Object)
14958     */
14959    public void setTag(final Object tag) {
14960        mTag = tag;
14961    }
14962
14963    /**
14964     * Returns the tag associated with this view and the specified key.
14965     *
14966     * @param key The key identifying the tag
14967     *
14968     * @return the Object stored in this view as a tag
14969     *
14970     * @see #setTag(int, Object)
14971     * @see #getTag()
14972     */
14973    public Object getTag(int key) {
14974        if (mKeyedTags != null) return mKeyedTags.get(key);
14975        return null;
14976    }
14977
14978    /**
14979     * Sets a tag associated with this view and a key. A tag can be used
14980     * to mark a view in its hierarchy and does not have to be unique within
14981     * the hierarchy. Tags can also be used to store data within a view
14982     * without resorting to another data structure.
14983     *
14984     * The specified key should be an id declared in the resources of the
14985     * application to ensure it is unique (see the <a
14986     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14987     * Keys identified as belonging to
14988     * the Android framework or not associated with any package will cause
14989     * an {@link IllegalArgumentException} to be thrown.
14990     *
14991     * @param key The key identifying the tag
14992     * @param tag An Object to tag the view with
14993     *
14994     * @throws IllegalArgumentException If they specified key is not valid
14995     *
14996     * @see #setTag(Object)
14997     * @see #getTag(int)
14998     */
14999    public void setTag(int key, final Object tag) {
15000        // If the package id is 0x00 or 0x01, it's either an undefined package
15001        // or a framework id
15002        if ((key >>> 24) < 2) {
15003            throw new IllegalArgumentException("The key must be an application-specific "
15004                    + "resource id.");
15005        }
15006
15007        setKeyedTag(key, tag);
15008    }
15009
15010    /**
15011     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15012     * framework id.
15013     *
15014     * @hide
15015     */
15016    public void setTagInternal(int key, Object tag) {
15017        if ((key >>> 24) != 0x1) {
15018            throw new IllegalArgumentException("The key must be a framework-specific "
15019                    + "resource id.");
15020        }
15021
15022        setKeyedTag(key, tag);
15023    }
15024
15025    private void setKeyedTag(int key, Object tag) {
15026        if (mKeyedTags == null) {
15027            mKeyedTags = new SparseArray<Object>();
15028        }
15029
15030        mKeyedTags.put(key, tag);
15031    }
15032
15033    /**
15034     * Prints information about this view in the log output, with the tag
15035     * {@link #VIEW_LOG_TAG}.
15036     *
15037     * @hide
15038     */
15039    public void debug() {
15040        debug(0);
15041    }
15042
15043    /**
15044     * Prints information about this view in the log output, with the tag
15045     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15046     * indentation defined by the <code>depth</code>.
15047     *
15048     * @param depth the indentation level
15049     *
15050     * @hide
15051     */
15052    protected void debug(int depth) {
15053        String output = debugIndent(depth - 1);
15054
15055        output += "+ " + this;
15056        int id = getId();
15057        if (id != -1) {
15058            output += " (id=" + id + ")";
15059        }
15060        Object tag = getTag();
15061        if (tag != null) {
15062            output += " (tag=" + tag + ")";
15063        }
15064        Log.d(VIEW_LOG_TAG, output);
15065
15066        if ((mPrivateFlags & FOCUSED) != 0) {
15067            output = debugIndent(depth) + " FOCUSED";
15068            Log.d(VIEW_LOG_TAG, output);
15069        }
15070
15071        output = debugIndent(depth);
15072        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15073                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15074                + "} ";
15075        Log.d(VIEW_LOG_TAG, output);
15076
15077        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15078                || mPaddingBottom != 0) {
15079            output = debugIndent(depth);
15080            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15081                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15082            Log.d(VIEW_LOG_TAG, output);
15083        }
15084
15085        output = debugIndent(depth);
15086        output += "mMeasureWidth=" + mMeasuredWidth +
15087                " mMeasureHeight=" + mMeasuredHeight;
15088        Log.d(VIEW_LOG_TAG, output);
15089
15090        output = debugIndent(depth);
15091        if (mLayoutParams == null) {
15092            output += "BAD! no layout params";
15093        } else {
15094            output = mLayoutParams.debug(output);
15095        }
15096        Log.d(VIEW_LOG_TAG, output);
15097
15098        output = debugIndent(depth);
15099        output += "flags={";
15100        output += View.printFlags(mViewFlags);
15101        output += "}";
15102        Log.d(VIEW_LOG_TAG, output);
15103
15104        output = debugIndent(depth);
15105        output += "privateFlags={";
15106        output += View.printPrivateFlags(mPrivateFlags);
15107        output += "}";
15108        Log.d(VIEW_LOG_TAG, output);
15109    }
15110
15111    /**
15112     * Creates a string of whitespaces used for indentation.
15113     *
15114     * @param depth the indentation level
15115     * @return a String containing (depth * 2 + 3) * 2 white spaces
15116     *
15117     * @hide
15118     */
15119    protected static String debugIndent(int depth) {
15120        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15121        for (int i = 0; i < (depth * 2) + 3; i++) {
15122            spaces.append(' ').append(' ');
15123        }
15124        return spaces.toString();
15125    }
15126
15127    /**
15128     * <p>Return the offset of the widget's text baseline from the widget's top
15129     * boundary. If this widget does not support baseline alignment, this
15130     * method returns -1. </p>
15131     *
15132     * @return the offset of the baseline within the widget's bounds or -1
15133     *         if baseline alignment is not supported
15134     */
15135    @ViewDebug.ExportedProperty(category = "layout")
15136    public int getBaseline() {
15137        return -1;
15138    }
15139
15140    /**
15141     * Call this when something has changed which has invalidated the
15142     * layout of this view. This will schedule a layout pass of the view
15143     * tree.
15144     */
15145    public void requestLayout() {
15146        mPrivateFlags |= FORCE_LAYOUT;
15147        mPrivateFlags |= INVALIDATED;
15148
15149        if (mLayoutParams != null) {
15150            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
15151        }
15152
15153        if (mParent != null && !mParent.isLayoutRequested()) {
15154            mParent.requestLayout();
15155        }
15156    }
15157
15158    /**
15159     * Forces this view to be laid out during the next layout pass.
15160     * This method does not call requestLayout() or forceLayout()
15161     * on the parent.
15162     */
15163    public void forceLayout() {
15164        mPrivateFlags |= FORCE_LAYOUT;
15165        mPrivateFlags |= INVALIDATED;
15166    }
15167
15168    /**
15169     * <p>
15170     * This is called to find out how big a view should be. The parent
15171     * supplies constraint information in the width and height parameters.
15172     * </p>
15173     *
15174     * <p>
15175     * The actual measurement work of a view is performed in
15176     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15177     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15178     * </p>
15179     *
15180     *
15181     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15182     *        parent
15183     * @param heightMeasureSpec Vertical space requirements as imposed by the
15184     *        parent
15185     *
15186     * @see #onMeasure(int, int)
15187     */
15188    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15189        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
15190                widthMeasureSpec != mOldWidthMeasureSpec ||
15191                heightMeasureSpec != mOldHeightMeasureSpec) {
15192
15193            // first clears the measured dimension flag
15194            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
15195
15196            // measure ourselves, this should set the measured dimension flag back
15197            onMeasure(widthMeasureSpec, heightMeasureSpec);
15198
15199            // flag not set, setMeasuredDimension() was not invoked, we raise
15200            // an exception to warn the developer
15201            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
15202                throw new IllegalStateException("onMeasure() did not set the"
15203                        + " measured dimension by calling"
15204                        + " setMeasuredDimension()");
15205            }
15206
15207            mPrivateFlags |= LAYOUT_REQUIRED;
15208        }
15209
15210        mOldWidthMeasureSpec = widthMeasureSpec;
15211        mOldHeightMeasureSpec = heightMeasureSpec;
15212    }
15213
15214    /**
15215     * <p>
15216     * Measure the view and its content to determine the measured width and the
15217     * measured height. This method is invoked by {@link #measure(int, int)} and
15218     * should be overriden by subclasses to provide accurate and efficient
15219     * measurement of their contents.
15220     * </p>
15221     *
15222     * <p>
15223     * <strong>CONTRACT:</strong> When overriding this method, you
15224     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15225     * measured width and height of this view. Failure to do so will trigger an
15226     * <code>IllegalStateException</code>, thrown by
15227     * {@link #measure(int, int)}. Calling the superclass'
15228     * {@link #onMeasure(int, int)} is a valid use.
15229     * </p>
15230     *
15231     * <p>
15232     * The base class implementation of measure defaults to the background size,
15233     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15234     * override {@link #onMeasure(int, int)} to provide better measurements of
15235     * their content.
15236     * </p>
15237     *
15238     * <p>
15239     * If this method is overridden, it is the subclass's responsibility to make
15240     * sure the measured height and width are at least the view's minimum height
15241     * and width ({@link #getSuggestedMinimumHeight()} and
15242     * {@link #getSuggestedMinimumWidth()}).
15243     * </p>
15244     *
15245     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15246     *                         The requirements are encoded with
15247     *                         {@link android.view.View.MeasureSpec}.
15248     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15249     *                         The requirements are encoded with
15250     *                         {@link android.view.View.MeasureSpec}.
15251     *
15252     * @see #getMeasuredWidth()
15253     * @see #getMeasuredHeight()
15254     * @see #setMeasuredDimension(int, int)
15255     * @see #getSuggestedMinimumHeight()
15256     * @see #getSuggestedMinimumWidth()
15257     * @see android.view.View.MeasureSpec#getMode(int)
15258     * @see android.view.View.MeasureSpec#getSize(int)
15259     */
15260    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15261        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15262                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15263    }
15264
15265    /**
15266     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15267     * measured width and measured height. Failing to do so will trigger an
15268     * exception at measurement time.</p>
15269     *
15270     * @param measuredWidth The measured width of this view.  May be a complex
15271     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15272     * {@link #MEASURED_STATE_TOO_SMALL}.
15273     * @param measuredHeight The measured height of this view.  May be a complex
15274     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15275     * {@link #MEASURED_STATE_TOO_SMALL}.
15276     */
15277    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15278        mMeasuredWidth = measuredWidth;
15279        mMeasuredHeight = measuredHeight;
15280
15281        mPrivateFlags |= MEASURED_DIMENSION_SET;
15282    }
15283
15284    /**
15285     * Merge two states as returned by {@link #getMeasuredState()}.
15286     * @param curState The current state as returned from a view or the result
15287     * of combining multiple views.
15288     * @param newState The new view state to combine.
15289     * @return Returns a new integer reflecting the combination of the two
15290     * states.
15291     */
15292    public static int combineMeasuredStates(int curState, int newState) {
15293        return curState | newState;
15294    }
15295
15296    /**
15297     * Version of {@link #resolveSizeAndState(int, int, int)}
15298     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15299     */
15300    public static int resolveSize(int size, int measureSpec) {
15301        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15302    }
15303
15304    /**
15305     * Utility to reconcile a desired size and state, with constraints imposed
15306     * by a MeasureSpec.  Will take the desired size, unless a different size
15307     * is imposed by the constraints.  The returned value is a compound integer,
15308     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15309     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15310     * size is smaller than the size the view wants to be.
15311     *
15312     * @param size How big the view wants to be
15313     * @param measureSpec Constraints imposed by the parent
15314     * @return Size information bit mask as defined by
15315     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15316     */
15317    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15318        int result = size;
15319        int specMode = MeasureSpec.getMode(measureSpec);
15320        int specSize =  MeasureSpec.getSize(measureSpec);
15321        switch (specMode) {
15322        case MeasureSpec.UNSPECIFIED:
15323            result = size;
15324            break;
15325        case MeasureSpec.AT_MOST:
15326            if (specSize < size) {
15327                result = specSize | MEASURED_STATE_TOO_SMALL;
15328            } else {
15329                result = size;
15330            }
15331            break;
15332        case MeasureSpec.EXACTLY:
15333            result = specSize;
15334            break;
15335        }
15336        return result | (childMeasuredState&MEASURED_STATE_MASK);
15337    }
15338
15339    /**
15340     * Utility to return a default size. Uses the supplied size if the
15341     * MeasureSpec imposed no constraints. Will get larger if allowed
15342     * by the MeasureSpec.
15343     *
15344     * @param size Default size for this view
15345     * @param measureSpec Constraints imposed by the parent
15346     * @return The size this view should be.
15347     */
15348    public static int getDefaultSize(int size, int measureSpec) {
15349        int result = size;
15350        int specMode = MeasureSpec.getMode(measureSpec);
15351        int specSize = MeasureSpec.getSize(measureSpec);
15352
15353        switch (specMode) {
15354        case MeasureSpec.UNSPECIFIED:
15355            result = size;
15356            break;
15357        case MeasureSpec.AT_MOST:
15358        case MeasureSpec.EXACTLY:
15359            result = specSize;
15360            break;
15361        }
15362        return result;
15363    }
15364
15365    /**
15366     * Returns the suggested minimum height that the view should use. This
15367     * returns the maximum of the view's minimum height
15368     * and the background's minimum height
15369     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15370     * <p>
15371     * When being used in {@link #onMeasure(int, int)}, the caller should still
15372     * ensure the returned height is within the requirements of the parent.
15373     *
15374     * @return The suggested minimum height of the view.
15375     */
15376    protected int getSuggestedMinimumHeight() {
15377        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15378
15379    }
15380
15381    /**
15382     * Returns the suggested minimum width that the view should use. This
15383     * returns the maximum of the view's minimum width)
15384     * and the background's minimum width
15385     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15386     * <p>
15387     * When being used in {@link #onMeasure(int, int)}, the caller should still
15388     * ensure the returned width is within the requirements of the parent.
15389     *
15390     * @return The suggested minimum width of the view.
15391     */
15392    protected int getSuggestedMinimumWidth() {
15393        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15394    }
15395
15396    /**
15397     * Returns the minimum height of the view.
15398     *
15399     * @return the minimum height the view will try to be.
15400     *
15401     * @see #setMinimumHeight(int)
15402     *
15403     * @attr ref android.R.styleable#View_minHeight
15404     */
15405    public int getMinimumHeight() {
15406        return mMinHeight;
15407    }
15408
15409    /**
15410     * Sets the minimum height of the view. It is not guaranteed the view will
15411     * be able to achieve this minimum height (for example, if its parent layout
15412     * constrains it with less available height).
15413     *
15414     * @param minHeight The minimum height the view will try to be.
15415     *
15416     * @see #getMinimumHeight()
15417     *
15418     * @attr ref android.R.styleable#View_minHeight
15419     */
15420    public void setMinimumHeight(int minHeight) {
15421        mMinHeight = minHeight;
15422        requestLayout();
15423    }
15424
15425    /**
15426     * Returns the minimum width of the view.
15427     *
15428     * @return the minimum width the view will try to be.
15429     *
15430     * @see #setMinimumWidth(int)
15431     *
15432     * @attr ref android.R.styleable#View_minWidth
15433     */
15434    public int getMinimumWidth() {
15435        return mMinWidth;
15436    }
15437
15438    /**
15439     * Sets the minimum width of the view. It is not guaranteed the view will
15440     * be able to achieve this minimum width (for example, if its parent layout
15441     * constrains it with less available width).
15442     *
15443     * @param minWidth The minimum width the view will try to be.
15444     *
15445     * @see #getMinimumWidth()
15446     *
15447     * @attr ref android.R.styleable#View_minWidth
15448     */
15449    public void setMinimumWidth(int minWidth) {
15450        mMinWidth = minWidth;
15451        requestLayout();
15452
15453    }
15454
15455    /**
15456     * Get the animation currently associated with this view.
15457     *
15458     * @return The animation that is currently playing or
15459     *         scheduled to play for this view.
15460     */
15461    public Animation getAnimation() {
15462        return mCurrentAnimation;
15463    }
15464
15465    /**
15466     * Start the specified animation now.
15467     *
15468     * @param animation the animation to start now
15469     */
15470    public void startAnimation(Animation animation) {
15471        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15472        setAnimation(animation);
15473        invalidateParentCaches();
15474        invalidate(true);
15475    }
15476
15477    /**
15478     * Cancels any animations for this view.
15479     */
15480    public void clearAnimation() {
15481        if (mCurrentAnimation != null) {
15482            mCurrentAnimation.detach();
15483        }
15484        mCurrentAnimation = null;
15485        invalidateParentIfNeeded();
15486    }
15487
15488    /**
15489     * Sets the next animation to play for this view.
15490     * If you want the animation to play immediately, use
15491     * {@link #startAnimation(android.view.animation.Animation)} instead.
15492     * This method provides allows fine-grained
15493     * control over the start time and invalidation, but you
15494     * must make sure that 1) the animation has a start time set, and
15495     * 2) the view's parent (which controls animations on its children)
15496     * will be invalidated when the animation is supposed to
15497     * start.
15498     *
15499     * @param animation The next animation, or null.
15500     */
15501    public void setAnimation(Animation animation) {
15502        mCurrentAnimation = animation;
15503
15504        if (animation != null) {
15505            // If the screen is off assume the animation start time is now instead of
15506            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15507            // would cause the animation to start when the screen turns back on
15508            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15509                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15510                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15511            }
15512            animation.reset();
15513        }
15514    }
15515
15516    /**
15517     * Invoked by a parent ViewGroup to notify the start of the animation
15518     * currently associated with this view. If you override this method,
15519     * always call super.onAnimationStart();
15520     *
15521     * @see #setAnimation(android.view.animation.Animation)
15522     * @see #getAnimation()
15523     */
15524    protected void onAnimationStart() {
15525        mPrivateFlags |= ANIMATION_STARTED;
15526    }
15527
15528    /**
15529     * Invoked by a parent ViewGroup to notify the end of the animation
15530     * currently associated with this view. If you override this method,
15531     * always call super.onAnimationEnd();
15532     *
15533     * @see #setAnimation(android.view.animation.Animation)
15534     * @see #getAnimation()
15535     */
15536    protected void onAnimationEnd() {
15537        mPrivateFlags &= ~ANIMATION_STARTED;
15538    }
15539
15540    /**
15541     * Invoked if there is a Transform that involves alpha. Subclass that can
15542     * draw themselves with the specified alpha should return true, and then
15543     * respect that alpha when their onDraw() is called. If this returns false
15544     * then the view may be redirected to draw into an offscreen buffer to
15545     * fulfill the request, which will look fine, but may be slower than if the
15546     * subclass handles it internally. The default implementation returns false.
15547     *
15548     * @param alpha The alpha (0..255) to apply to the view's drawing
15549     * @return true if the view can draw with the specified alpha.
15550     */
15551    protected boolean onSetAlpha(int alpha) {
15552        return false;
15553    }
15554
15555    /**
15556     * This is used by the RootView to perform an optimization when
15557     * the view hierarchy contains one or several SurfaceView.
15558     * SurfaceView is always considered transparent, but its children are not,
15559     * therefore all View objects remove themselves from the global transparent
15560     * region (passed as a parameter to this function).
15561     *
15562     * @param region The transparent region for this ViewAncestor (window).
15563     *
15564     * @return Returns true if the effective visibility of the view at this
15565     * point is opaque, regardless of the transparent region; returns false
15566     * if it is possible for underlying windows to be seen behind the view.
15567     *
15568     * {@hide}
15569     */
15570    public boolean gatherTransparentRegion(Region region) {
15571        final AttachInfo attachInfo = mAttachInfo;
15572        if (region != null && attachInfo != null) {
15573            final int pflags = mPrivateFlags;
15574            if ((pflags & SKIP_DRAW) == 0) {
15575                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15576                // remove it from the transparent region.
15577                final int[] location = attachInfo.mTransparentLocation;
15578                getLocationInWindow(location);
15579                region.op(location[0], location[1], location[0] + mRight - mLeft,
15580                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15581            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15582                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15583                // exists, so we remove the background drawable's non-transparent
15584                // parts from this transparent region.
15585                applyDrawableToTransparentRegion(mBackground, region);
15586            }
15587        }
15588        return true;
15589    }
15590
15591    /**
15592     * Play a sound effect for this view.
15593     *
15594     * <p>The framework will play sound effects for some built in actions, such as
15595     * clicking, but you may wish to play these effects in your widget,
15596     * for instance, for internal navigation.
15597     *
15598     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15599     * {@link #isSoundEffectsEnabled()} is true.
15600     *
15601     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15602     */
15603    public void playSoundEffect(int soundConstant) {
15604        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15605            return;
15606        }
15607        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15608    }
15609
15610    /**
15611     * BZZZTT!!1!
15612     *
15613     * <p>Provide haptic feedback to the user for this view.
15614     *
15615     * <p>The framework will provide haptic feedback for some built in actions,
15616     * such as long presses, but you may wish to provide feedback for your
15617     * own widget.
15618     *
15619     * <p>The feedback will only be performed if
15620     * {@link #isHapticFeedbackEnabled()} is true.
15621     *
15622     * @param feedbackConstant One of the constants defined in
15623     * {@link HapticFeedbackConstants}
15624     */
15625    public boolean performHapticFeedback(int feedbackConstant) {
15626        return performHapticFeedback(feedbackConstant, 0);
15627    }
15628
15629    /**
15630     * BZZZTT!!1!
15631     *
15632     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15633     *
15634     * @param feedbackConstant One of the constants defined in
15635     * {@link HapticFeedbackConstants}
15636     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15637     */
15638    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15639        if (mAttachInfo == null) {
15640            return false;
15641        }
15642        //noinspection SimplifiableIfStatement
15643        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15644                && !isHapticFeedbackEnabled()) {
15645            return false;
15646        }
15647        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15648                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15649    }
15650
15651    /**
15652     * Request that the visibility of the status bar or other screen/window
15653     * decorations be changed.
15654     *
15655     * <p>This method is used to put the over device UI into temporary modes
15656     * where the user's attention is focused more on the application content,
15657     * by dimming or hiding surrounding system affordances.  This is typically
15658     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15659     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15660     * to be placed behind the action bar (and with these flags other system
15661     * affordances) so that smooth transitions between hiding and showing them
15662     * can be done.
15663     *
15664     * <p>Two representative examples of the use of system UI visibility is
15665     * implementing a content browsing application (like a magazine reader)
15666     * and a video playing application.
15667     *
15668     * <p>The first code shows a typical implementation of a View in a content
15669     * browsing application.  In this implementation, the application goes
15670     * into a content-oriented mode by hiding the status bar and action bar,
15671     * and putting the navigation elements into lights out mode.  The user can
15672     * then interact with content while in this mode.  Such an application should
15673     * provide an easy way for the user to toggle out of the mode (such as to
15674     * check information in the status bar or access notifications).  In the
15675     * implementation here, this is done simply by tapping on the content.
15676     *
15677     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15678     *      content}
15679     *
15680     * <p>This second code sample shows a typical implementation of a View
15681     * in a video playing application.  In this situation, while the video is
15682     * playing the application would like to go into a complete full-screen mode,
15683     * to use as much of the display as possible for the video.  When in this state
15684     * the user can not interact with the application; the system intercepts
15685     * touching on the screen to pop the UI out of full screen mode.  See
15686     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15687     *
15688     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15689     *      content}
15690     *
15691     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15692     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15693     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15694     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15695     */
15696    public void setSystemUiVisibility(int visibility) {
15697        if (visibility != mSystemUiVisibility) {
15698            mSystemUiVisibility = visibility;
15699            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15700                mParent.recomputeViewAttributes(this);
15701            }
15702        }
15703    }
15704
15705    /**
15706     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15707     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15708     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15709     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15710     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15711     */
15712    public int getSystemUiVisibility() {
15713        return mSystemUiVisibility;
15714    }
15715
15716    /**
15717     * Returns the current system UI visibility that is currently set for
15718     * the entire window.  This is the combination of the
15719     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15720     * views in the window.
15721     */
15722    public int getWindowSystemUiVisibility() {
15723        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15724    }
15725
15726    /**
15727     * Override to find out when the window's requested system UI visibility
15728     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15729     * This is different from the callbacks recieved through
15730     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15731     * in that this is only telling you about the local request of the window,
15732     * not the actual values applied by the system.
15733     */
15734    public void onWindowSystemUiVisibilityChanged(int visible) {
15735    }
15736
15737    /**
15738     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15739     * the view hierarchy.
15740     */
15741    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15742        onWindowSystemUiVisibilityChanged(visible);
15743    }
15744
15745    /**
15746     * Set a listener to receive callbacks when the visibility of the system bar changes.
15747     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15748     */
15749    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15750        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15751        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15752            mParent.recomputeViewAttributes(this);
15753        }
15754    }
15755
15756    /**
15757     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15758     * the view hierarchy.
15759     */
15760    public void dispatchSystemUiVisibilityChanged(int visibility) {
15761        ListenerInfo li = mListenerInfo;
15762        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15763            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15764                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15765        }
15766    }
15767
15768    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15769        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15770        if (val != mSystemUiVisibility) {
15771            setSystemUiVisibility(val);
15772            return true;
15773        }
15774        return false;
15775    }
15776
15777    /** @hide */
15778    public void setDisabledSystemUiVisibility(int flags) {
15779        if (mAttachInfo != null) {
15780            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15781                mAttachInfo.mDisabledSystemUiVisibility = flags;
15782                if (mParent != null) {
15783                    mParent.recomputeViewAttributes(this);
15784                }
15785            }
15786        }
15787    }
15788
15789    /**
15790     * Creates an image that the system displays during the drag and drop
15791     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15792     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15793     * appearance as the given View. The default also positions the center of the drag shadow
15794     * directly under the touch point. If no View is provided (the constructor with no parameters
15795     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15796     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15797     * default is an invisible drag shadow.
15798     * <p>
15799     * You are not required to use the View you provide to the constructor as the basis of the
15800     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15801     * anything you want as the drag shadow.
15802     * </p>
15803     * <p>
15804     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15805     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15806     *  size and position of the drag shadow. It uses this data to construct a
15807     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15808     *  so that your application can draw the shadow image in the Canvas.
15809     * </p>
15810     *
15811     * <div class="special reference">
15812     * <h3>Developer Guides</h3>
15813     * <p>For a guide to implementing drag and drop features, read the
15814     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15815     * </div>
15816     */
15817    public static class DragShadowBuilder {
15818        private final WeakReference<View> mView;
15819
15820        /**
15821         * Constructs a shadow image builder based on a View. By default, the resulting drag
15822         * shadow will have the same appearance and dimensions as the View, with the touch point
15823         * over the center of the View.
15824         * @param view A View. Any View in scope can be used.
15825         */
15826        public DragShadowBuilder(View view) {
15827            mView = new WeakReference<View>(view);
15828        }
15829
15830        /**
15831         * Construct a shadow builder object with no associated View.  This
15832         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15833         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15834         * to supply the drag shadow's dimensions and appearance without
15835         * reference to any View object. If they are not overridden, then the result is an
15836         * invisible drag shadow.
15837         */
15838        public DragShadowBuilder() {
15839            mView = new WeakReference<View>(null);
15840        }
15841
15842        /**
15843         * Returns the View object that had been passed to the
15844         * {@link #View.DragShadowBuilder(View)}
15845         * constructor.  If that View parameter was {@code null} or if the
15846         * {@link #View.DragShadowBuilder()}
15847         * constructor was used to instantiate the builder object, this method will return
15848         * null.
15849         *
15850         * @return The View object associate with this builder object.
15851         */
15852        @SuppressWarnings({"JavadocReference"})
15853        final public View getView() {
15854            return mView.get();
15855        }
15856
15857        /**
15858         * Provides the metrics for the shadow image. These include the dimensions of
15859         * the shadow image, and the point within that shadow that should
15860         * be centered under the touch location while dragging.
15861         * <p>
15862         * The default implementation sets the dimensions of the shadow to be the
15863         * same as the dimensions of the View itself and centers the shadow under
15864         * the touch point.
15865         * </p>
15866         *
15867         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15868         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15869         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15870         * image.
15871         *
15872         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15873         * shadow image that should be underneath the touch point during the drag and drop
15874         * operation. Your application must set {@link android.graphics.Point#x} to the
15875         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15876         */
15877        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15878            final View view = mView.get();
15879            if (view != null) {
15880                shadowSize.set(view.getWidth(), view.getHeight());
15881                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15882            } else {
15883                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15884            }
15885        }
15886
15887        /**
15888         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15889         * based on the dimensions it received from the
15890         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15891         *
15892         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15893         */
15894        public void onDrawShadow(Canvas canvas) {
15895            final View view = mView.get();
15896            if (view != null) {
15897                view.draw(canvas);
15898            } else {
15899                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15900            }
15901        }
15902    }
15903
15904    /**
15905     * Starts a drag and drop operation. When your application calls this method, it passes a
15906     * {@link android.view.View.DragShadowBuilder} object to the system. The
15907     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15908     * to get metrics for the drag shadow, and then calls the object's
15909     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15910     * <p>
15911     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15912     *  drag events to all the View objects in your application that are currently visible. It does
15913     *  this either by calling the View object's drag listener (an implementation of
15914     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15915     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15916     *  Both are passed a {@link android.view.DragEvent} object that has a
15917     *  {@link android.view.DragEvent#getAction()} value of
15918     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15919     * </p>
15920     * <p>
15921     * Your application can invoke startDrag() on any attached View object. The View object does not
15922     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15923     * be related to the View the user selected for dragging.
15924     * </p>
15925     * @param data A {@link android.content.ClipData} object pointing to the data to be
15926     * transferred by the drag and drop operation.
15927     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15928     * drag shadow.
15929     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15930     * drop operation. This Object is put into every DragEvent object sent by the system during the
15931     * current drag.
15932     * <p>
15933     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15934     * to the target Views. For example, it can contain flags that differentiate between a
15935     * a copy operation and a move operation.
15936     * </p>
15937     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15938     * so the parameter should be set to 0.
15939     * @return {@code true} if the method completes successfully, or
15940     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15941     * do a drag, and so no drag operation is in progress.
15942     */
15943    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15944            Object myLocalState, int flags) {
15945        if (ViewDebug.DEBUG_DRAG) {
15946            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15947        }
15948        boolean okay = false;
15949
15950        Point shadowSize = new Point();
15951        Point shadowTouchPoint = new Point();
15952        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15953
15954        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15955                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15956            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15957        }
15958
15959        if (ViewDebug.DEBUG_DRAG) {
15960            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15961                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15962        }
15963        Surface surface = new Surface();
15964        try {
15965            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15966                    flags, shadowSize.x, shadowSize.y, surface);
15967            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15968                    + " surface=" + surface);
15969            if (token != null) {
15970                Canvas canvas = surface.lockCanvas(null);
15971                try {
15972                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15973                    shadowBuilder.onDrawShadow(canvas);
15974                } finally {
15975                    surface.unlockCanvasAndPost(canvas);
15976                }
15977
15978                final ViewRootImpl root = getViewRootImpl();
15979
15980                // Cache the local state object for delivery with DragEvents
15981                root.setLocalDragState(myLocalState);
15982
15983                // repurpose 'shadowSize' for the last touch point
15984                root.getLastTouchPoint(shadowSize);
15985
15986                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15987                        shadowSize.x, shadowSize.y,
15988                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15989                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15990
15991                // Off and running!  Release our local surface instance; the drag
15992                // shadow surface is now managed by the system process.
15993                surface.release();
15994            }
15995        } catch (Exception e) {
15996            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15997            surface.destroy();
15998        }
15999
16000        return okay;
16001    }
16002
16003    /**
16004     * Handles drag events sent by the system following a call to
16005     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16006     *<p>
16007     * When the system calls this method, it passes a
16008     * {@link android.view.DragEvent} object. A call to
16009     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16010     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16011     * operation.
16012     * @param event The {@link android.view.DragEvent} sent by the system.
16013     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16014     * in DragEvent, indicating the type of drag event represented by this object.
16015     * @return {@code true} if the method was successful, otherwise {@code false}.
16016     * <p>
16017     *  The method should return {@code true} in response to an action type of
16018     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16019     *  operation.
16020     * </p>
16021     * <p>
16022     *  The method should also return {@code true} in response to an action type of
16023     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16024     *  {@code false} if it didn't.
16025     * </p>
16026     */
16027    public boolean onDragEvent(DragEvent event) {
16028        return false;
16029    }
16030
16031    /**
16032     * Detects if this View is enabled and has a drag event listener.
16033     * If both are true, then it calls the drag event listener with the
16034     * {@link android.view.DragEvent} it received. If the drag event listener returns
16035     * {@code true}, then dispatchDragEvent() returns {@code true}.
16036     * <p>
16037     * For all other cases, the method calls the
16038     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16039     * method and returns its result.
16040     * </p>
16041     * <p>
16042     * This ensures that a drag event is always consumed, even if the View does not have a drag
16043     * event listener. However, if the View has a listener and the listener returns true, then
16044     * onDragEvent() is not called.
16045     * </p>
16046     */
16047    public boolean dispatchDragEvent(DragEvent event) {
16048        //noinspection SimplifiableIfStatement
16049        ListenerInfo li = mListenerInfo;
16050        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16051                && li.mOnDragListener.onDrag(this, event)) {
16052            return true;
16053        }
16054        return onDragEvent(event);
16055    }
16056
16057    boolean canAcceptDrag() {
16058        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
16059    }
16060
16061    /**
16062     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16063     * it is ever exposed at all.
16064     * @hide
16065     */
16066    public void onCloseSystemDialogs(String reason) {
16067    }
16068
16069    /**
16070     * Given a Drawable whose bounds have been set to draw into this view,
16071     * update a Region being computed for
16072     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16073     * that any non-transparent parts of the Drawable are removed from the
16074     * given transparent region.
16075     *
16076     * @param dr The Drawable whose transparency is to be applied to the region.
16077     * @param region A Region holding the current transparency information,
16078     * where any parts of the region that are set are considered to be
16079     * transparent.  On return, this region will be modified to have the
16080     * transparency information reduced by the corresponding parts of the
16081     * Drawable that are not transparent.
16082     * {@hide}
16083     */
16084    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16085        if (DBG) {
16086            Log.i("View", "Getting transparent region for: " + this);
16087        }
16088        final Region r = dr.getTransparentRegion();
16089        final Rect db = dr.getBounds();
16090        final AttachInfo attachInfo = mAttachInfo;
16091        if (r != null && attachInfo != null) {
16092            final int w = getRight()-getLeft();
16093            final int h = getBottom()-getTop();
16094            if (db.left > 0) {
16095                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16096                r.op(0, 0, db.left, h, Region.Op.UNION);
16097            }
16098            if (db.right < w) {
16099                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16100                r.op(db.right, 0, w, h, Region.Op.UNION);
16101            }
16102            if (db.top > 0) {
16103                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16104                r.op(0, 0, w, db.top, Region.Op.UNION);
16105            }
16106            if (db.bottom < h) {
16107                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16108                r.op(0, db.bottom, w, h, Region.Op.UNION);
16109            }
16110            final int[] location = attachInfo.mTransparentLocation;
16111            getLocationInWindow(location);
16112            r.translate(location[0], location[1]);
16113            region.op(r, Region.Op.INTERSECT);
16114        } else {
16115            region.op(db, Region.Op.DIFFERENCE);
16116        }
16117    }
16118
16119    private void checkForLongClick(int delayOffset) {
16120        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16121            mHasPerformedLongPress = false;
16122
16123            if (mPendingCheckForLongPress == null) {
16124                mPendingCheckForLongPress = new CheckForLongPress();
16125            }
16126            mPendingCheckForLongPress.rememberWindowAttachCount();
16127            postDelayed(mPendingCheckForLongPress,
16128                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16129        }
16130    }
16131
16132    /**
16133     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16134     * LayoutInflater} class, which provides a full range of options for view inflation.
16135     *
16136     * @param context The Context object for your activity or application.
16137     * @param resource The resource ID to inflate
16138     * @param root A view group that will be the parent.  Used to properly inflate the
16139     * layout_* parameters.
16140     * @see LayoutInflater
16141     */
16142    public static View inflate(Context context, int resource, ViewGroup root) {
16143        LayoutInflater factory = LayoutInflater.from(context);
16144        return factory.inflate(resource, root);
16145    }
16146
16147    /**
16148     * Scroll the view with standard behavior for scrolling beyond the normal
16149     * content boundaries. Views that call this method should override
16150     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16151     * results of an over-scroll operation.
16152     *
16153     * Views can use this method to handle any touch or fling-based scrolling.
16154     *
16155     * @param deltaX Change in X in pixels
16156     * @param deltaY Change in Y in pixels
16157     * @param scrollX Current X scroll value in pixels before applying deltaX
16158     * @param scrollY Current Y scroll value in pixels before applying deltaY
16159     * @param scrollRangeX Maximum content scroll range along the X axis
16160     * @param scrollRangeY Maximum content scroll range along the Y axis
16161     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16162     *          along the X axis.
16163     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16164     *          along the Y axis.
16165     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16166     * @return true if scrolling was clamped to an over-scroll boundary along either
16167     *          axis, false otherwise.
16168     */
16169    @SuppressWarnings({"UnusedParameters"})
16170    protected boolean overScrollBy(int deltaX, int deltaY,
16171            int scrollX, int scrollY,
16172            int scrollRangeX, int scrollRangeY,
16173            int maxOverScrollX, int maxOverScrollY,
16174            boolean isTouchEvent) {
16175        final int overScrollMode = mOverScrollMode;
16176        final boolean canScrollHorizontal =
16177                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16178        final boolean canScrollVertical =
16179                computeVerticalScrollRange() > computeVerticalScrollExtent();
16180        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16181                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16182        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16183                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16184
16185        int newScrollX = scrollX + deltaX;
16186        if (!overScrollHorizontal) {
16187            maxOverScrollX = 0;
16188        }
16189
16190        int newScrollY = scrollY + deltaY;
16191        if (!overScrollVertical) {
16192            maxOverScrollY = 0;
16193        }
16194
16195        // Clamp values if at the limits and record
16196        final int left = -maxOverScrollX;
16197        final int right = maxOverScrollX + scrollRangeX;
16198        final int top = -maxOverScrollY;
16199        final int bottom = maxOverScrollY + scrollRangeY;
16200
16201        boolean clampedX = false;
16202        if (newScrollX > right) {
16203            newScrollX = right;
16204            clampedX = true;
16205        } else if (newScrollX < left) {
16206            newScrollX = left;
16207            clampedX = true;
16208        }
16209
16210        boolean clampedY = false;
16211        if (newScrollY > bottom) {
16212            newScrollY = bottom;
16213            clampedY = true;
16214        } else if (newScrollY < top) {
16215            newScrollY = top;
16216            clampedY = true;
16217        }
16218
16219        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16220
16221        return clampedX || clampedY;
16222    }
16223
16224    /**
16225     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16226     * respond to the results of an over-scroll operation.
16227     *
16228     * @param scrollX New X scroll value in pixels
16229     * @param scrollY New Y scroll value in pixels
16230     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16231     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16232     */
16233    protected void onOverScrolled(int scrollX, int scrollY,
16234            boolean clampedX, boolean clampedY) {
16235        // Intentionally empty.
16236    }
16237
16238    /**
16239     * Returns the over-scroll mode for this view. The result will be
16240     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16241     * (allow over-scrolling only if the view content is larger than the container),
16242     * or {@link #OVER_SCROLL_NEVER}.
16243     *
16244     * @return This view's over-scroll mode.
16245     */
16246    public int getOverScrollMode() {
16247        return mOverScrollMode;
16248    }
16249
16250    /**
16251     * Set the over-scroll mode for this view. Valid over-scroll modes are
16252     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16253     * (allow over-scrolling only if the view content is larger than the container),
16254     * or {@link #OVER_SCROLL_NEVER}.
16255     *
16256     * Setting the over-scroll mode of a view will have an effect only if the
16257     * view is capable of scrolling.
16258     *
16259     * @param overScrollMode The new over-scroll mode for this view.
16260     */
16261    public void setOverScrollMode(int overScrollMode) {
16262        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16263                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16264                overScrollMode != OVER_SCROLL_NEVER) {
16265            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16266        }
16267        mOverScrollMode = overScrollMode;
16268    }
16269
16270    /**
16271     * Gets a scale factor that determines the distance the view should scroll
16272     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16273     * @return The vertical scroll scale factor.
16274     * @hide
16275     */
16276    protected float getVerticalScrollFactor() {
16277        if (mVerticalScrollFactor == 0) {
16278            TypedValue outValue = new TypedValue();
16279            if (!mContext.getTheme().resolveAttribute(
16280                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16281                throw new IllegalStateException(
16282                        "Expected theme to define listPreferredItemHeight.");
16283            }
16284            mVerticalScrollFactor = outValue.getDimension(
16285                    mContext.getResources().getDisplayMetrics());
16286        }
16287        return mVerticalScrollFactor;
16288    }
16289
16290    /**
16291     * Gets a scale factor that determines the distance the view should scroll
16292     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16293     * @return The horizontal scroll scale factor.
16294     * @hide
16295     */
16296    protected float getHorizontalScrollFactor() {
16297        // TODO: Should use something else.
16298        return getVerticalScrollFactor();
16299    }
16300
16301    /**
16302     * Return the value specifying the text direction or policy that was set with
16303     * {@link #setTextDirection(int)}.
16304     *
16305     * @return the defined text direction. It can be one of:
16306     *
16307     * {@link #TEXT_DIRECTION_INHERIT},
16308     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16309     * {@link #TEXT_DIRECTION_ANY_RTL},
16310     * {@link #TEXT_DIRECTION_LTR},
16311     * {@link #TEXT_DIRECTION_RTL},
16312     * {@link #TEXT_DIRECTION_LOCALE}
16313     * @hide
16314     */
16315    @ViewDebug.ExportedProperty(category = "text", mapping = {
16316            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16317            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16318            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16319            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16320            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16321            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16322    })
16323    public int getTextDirection() {
16324        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16325    }
16326
16327    /**
16328     * Set the text direction.
16329     *
16330     * @param textDirection the direction to set. Should be one of:
16331     *
16332     * {@link #TEXT_DIRECTION_INHERIT},
16333     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16334     * {@link #TEXT_DIRECTION_ANY_RTL},
16335     * {@link #TEXT_DIRECTION_LTR},
16336     * {@link #TEXT_DIRECTION_RTL},
16337     * {@link #TEXT_DIRECTION_LOCALE}
16338     * @hide
16339     */
16340    public void setTextDirection(int textDirection) {
16341        if (getTextDirection() != textDirection) {
16342            // Reset the current text direction and the resolved one
16343            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16344            resetResolvedTextDirection();
16345            // Set the new text direction
16346            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16347            // Refresh
16348            requestLayout();
16349            invalidate(true);
16350        }
16351    }
16352
16353    /**
16354     * Return the resolved text direction.
16355     *
16356     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16357     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16358     * up the parent chain of the view. if there is no parent, then it will return the default
16359     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16360     *
16361     * @return the resolved text direction. Returns one of:
16362     *
16363     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16364     * {@link #TEXT_DIRECTION_ANY_RTL},
16365     * {@link #TEXT_DIRECTION_LTR},
16366     * {@link #TEXT_DIRECTION_RTL},
16367     * {@link #TEXT_DIRECTION_LOCALE}
16368     * @hide
16369     */
16370    public int getResolvedTextDirection() {
16371        // The text direction will be resolved only if needed
16372        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16373            resolveTextDirection();
16374        }
16375        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16376    }
16377
16378    /**
16379     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16380     * resolution is done.
16381     * @hide
16382     */
16383    public void resolveTextDirection() {
16384        // Reset any previous text direction resolution
16385        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16386
16387        if (hasRtlSupport()) {
16388            // Set resolved text direction flag depending on text direction flag
16389            final int textDirection = getTextDirection();
16390            switch(textDirection) {
16391                case TEXT_DIRECTION_INHERIT:
16392                    if (canResolveTextDirection()) {
16393                        ViewGroup viewGroup = ((ViewGroup) mParent);
16394
16395                        // Set current resolved direction to the same value as the parent's one
16396                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16397                        switch (parentResolvedDirection) {
16398                            case TEXT_DIRECTION_FIRST_STRONG:
16399                            case TEXT_DIRECTION_ANY_RTL:
16400                            case TEXT_DIRECTION_LTR:
16401                            case TEXT_DIRECTION_RTL:
16402                            case TEXT_DIRECTION_LOCALE:
16403                                mPrivateFlags2 |=
16404                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16405                                break;
16406                            default:
16407                                // Default resolved direction is "first strong" heuristic
16408                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16409                        }
16410                    } else {
16411                        // We cannot do the resolution if there is no parent, so use the default one
16412                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16413                    }
16414                    break;
16415                case TEXT_DIRECTION_FIRST_STRONG:
16416                case TEXT_DIRECTION_ANY_RTL:
16417                case TEXT_DIRECTION_LTR:
16418                case TEXT_DIRECTION_RTL:
16419                case TEXT_DIRECTION_LOCALE:
16420                    // Resolved direction is the same as text direction
16421                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16422                    break;
16423                default:
16424                    // Default resolved direction is "first strong" heuristic
16425                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16426            }
16427        } else {
16428            // Default resolved direction is "first strong" heuristic
16429            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16430        }
16431
16432        // Set to resolved
16433        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16434        onResolvedTextDirectionChanged();
16435    }
16436
16437    /**
16438     * Called when text direction has been resolved. Subclasses that care about text direction
16439     * resolution should override this method.
16440     *
16441     * The default implementation does nothing.
16442     * @hide
16443     */
16444    public void onResolvedTextDirectionChanged() {
16445    }
16446
16447    /**
16448     * Check if text direction resolution can be done.
16449     *
16450     * @return true if text direction resolution can be done otherwise return false.
16451     * @hide
16452     */
16453    public boolean canResolveTextDirection() {
16454        switch (getTextDirection()) {
16455            case TEXT_DIRECTION_INHERIT:
16456                return (mParent != null) && (mParent instanceof ViewGroup);
16457            default:
16458                return true;
16459        }
16460    }
16461
16462    /**
16463     * Reset resolved text direction. Text direction can be resolved with a call to
16464     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16465     * reset is done.
16466     * @hide
16467     */
16468    public void resetResolvedTextDirection() {
16469        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16470        onResolvedTextDirectionReset();
16471    }
16472
16473    /**
16474     * Called when text direction is reset. Subclasses that care about text direction reset should
16475     * override this method and do a reset of the text direction of their children. The default
16476     * implementation does nothing.
16477     * @hide
16478     */
16479    public void onResolvedTextDirectionReset() {
16480    }
16481
16482    /**
16483     * Return the value specifying the text alignment or policy that was set with
16484     * {@link #setTextAlignment(int)}.
16485     *
16486     * @return the defined text alignment. It can be one of:
16487     *
16488     * {@link #TEXT_ALIGNMENT_INHERIT},
16489     * {@link #TEXT_ALIGNMENT_GRAVITY},
16490     * {@link #TEXT_ALIGNMENT_CENTER},
16491     * {@link #TEXT_ALIGNMENT_TEXT_START},
16492     * {@link #TEXT_ALIGNMENT_TEXT_END},
16493     * {@link #TEXT_ALIGNMENT_VIEW_START},
16494     * {@link #TEXT_ALIGNMENT_VIEW_END}
16495     * @hide
16496     */
16497    @ViewDebug.ExportedProperty(category = "text", mapping = {
16498            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16499            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16500            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16501            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16502            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16503            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16504            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16505    })
16506    public int getTextAlignment() {
16507        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16508    }
16509
16510    /**
16511     * Set the text alignment.
16512     *
16513     * @param textAlignment The text alignment to set. Should be one of
16514     *
16515     * {@link #TEXT_ALIGNMENT_INHERIT},
16516     * {@link #TEXT_ALIGNMENT_GRAVITY},
16517     * {@link #TEXT_ALIGNMENT_CENTER},
16518     * {@link #TEXT_ALIGNMENT_TEXT_START},
16519     * {@link #TEXT_ALIGNMENT_TEXT_END},
16520     * {@link #TEXT_ALIGNMENT_VIEW_START},
16521     * {@link #TEXT_ALIGNMENT_VIEW_END}
16522     *
16523     * @attr ref android.R.styleable#View_textAlignment
16524     * @hide
16525     */
16526    public void setTextAlignment(int textAlignment) {
16527        if (textAlignment != getTextAlignment()) {
16528            // Reset the current and resolved text alignment
16529            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16530            resetResolvedTextAlignment();
16531            // Set the new text alignment
16532            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16533            // Refresh
16534            requestLayout();
16535            invalidate(true);
16536        }
16537    }
16538
16539    /**
16540     * Return the resolved text alignment.
16541     *
16542     * The resolved text alignment. This needs resolution if the value is
16543     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16544     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16545     *
16546     * @return the resolved text alignment. Returns one of:
16547     *
16548     * {@link #TEXT_ALIGNMENT_GRAVITY},
16549     * {@link #TEXT_ALIGNMENT_CENTER},
16550     * {@link #TEXT_ALIGNMENT_TEXT_START},
16551     * {@link #TEXT_ALIGNMENT_TEXT_END},
16552     * {@link #TEXT_ALIGNMENT_VIEW_START},
16553     * {@link #TEXT_ALIGNMENT_VIEW_END}
16554     * @hide
16555     */
16556    @ViewDebug.ExportedProperty(category = "text", mapping = {
16557            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16558            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16559            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16560            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16561            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16562            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16563            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16564    })
16565    public int getResolvedTextAlignment() {
16566        // If text alignment is not resolved, then resolve it
16567        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16568            resolveTextAlignment();
16569        }
16570        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16571    }
16572
16573    /**
16574     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16575     * resolution is done.
16576     * @hide
16577     */
16578    public void resolveTextAlignment() {
16579        // Reset any previous text alignment resolution
16580        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16581
16582        if (hasRtlSupport()) {
16583            // Set resolved text alignment flag depending on text alignment flag
16584            final int textAlignment = getTextAlignment();
16585            switch (textAlignment) {
16586                case TEXT_ALIGNMENT_INHERIT:
16587                    // Check if we can resolve the text alignment
16588                    if (canResolveLayoutDirection() && mParent instanceof View) {
16589                        View view = (View) mParent;
16590
16591                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16592                        switch (parentResolvedTextAlignment) {
16593                            case TEXT_ALIGNMENT_GRAVITY:
16594                            case TEXT_ALIGNMENT_TEXT_START:
16595                            case TEXT_ALIGNMENT_TEXT_END:
16596                            case TEXT_ALIGNMENT_CENTER:
16597                            case TEXT_ALIGNMENT_VIEW_START:
16598                            case TEXT_ALIGNMENT_VIEW_END:
16599                                // Resolved text alignment is the same as the parent resolved
16600                                // text alignment
16601                                mPrivateFlags2 |=
16602                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16603                                break;
16604                            default:
16605                                // Use default resolved text alignment
16606                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16607                        }
16608                    }
16609                    else {
16610                        // We cannot do the resolution if there is no parent so use the default
16611                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16612                    }
16613                    break;
16614                case TEXT_ALIGNMENT_GRAVITY:
16615                case TEXT_ALIGNMENT_TEXT_START:
16616                case TEXT_ALIGNMENT_TEXT_END:
16617                case TEXT_ALIGNMENT_CENTER:
16618                case TEXT_ALIGNMENT_VIEW_START:
16619                case TEXT_ALIGNMENT_VIEW_END:
16620                    // Resolved text alignment is the same as text alignment
16621                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16622                    break;
16623                default:
16624                    // Use default resolved text alignment
16625                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16626            }
16627        } else {
16628            // Use default resolved text alignment
16629            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16630        }
16631
16632        // Set the resolved
16633        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16634        onResolvedTextAlignmentChanged();
16635    }
16636
16637    /**
16638     * Check if text alignment resolution can be done.
16639     *
16640     * @return true if text alignment resolution can be done otherwise return false.
16641     * @hide
16642     */
16643    public boolean canResolveTextAlignment() {
16644        switch (getTextAlignment()) {
16645            case TEXT_DIRECTION_INHERIT:
16646                return (mParent != null);
16647            default:
16648                return true;
16649        }
16650    }
16651
16652    /**
16653     * Called when text alignment has been resolved. Subclasses that care about text alignment
16654     * resolution should override this method.
16655     *
16656     * The default implementation does nothing.
16657     * @hide
16658     */
16659    public void onResolvedTextAlignmentChanged() {
16660    }
16661
16662    /**
16663     * Reset resolved text alignment. Text alignment can be resolved with a call to
16664     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16665     * reset is done.
16666     * @hide
16667     */
16668    public void resetResolvedTextAlignment() {
16669        // Reset any previous text alignment resolution
16670        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16671        onResolvedTextAlignmentReset();
16672    }
16673
16674    /**
16675     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16676     * override this method and do a reset of the text alignment of their children. The default
16677     * implementation does nothing.
16678     * @hide
16679     */
16680    public void onResolvedTextAlignmentReset() {
16681    }
16682
16683    //
16684    // Properties
16685    //
16686    /**
16687     * A Property wrapper around the <code>alpha</code> functionality handled by the
16688     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16689     */
16690    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16691        @Override
16692        public void setValue(View object, float value) {
16693            object.setAlpha(value);
16694        }
16695
16696        @Override
16697        public Float get(View object) {
16698            return object.getAlpha();
16699        }
16700    };
16701
16702    /**
16703     * A Property wrapper around the <code>translationX</code> functionality handled by the
16704     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16705     */
16706    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16707        @Override
16708        public void setValue(View object, float value) {
16709            object.setTranslationX(value);
16710        }
16711
16712                @Override
16713        public Float get(View object) {
16714            return object.getTranslationX();
16715        }
16716    };
16717
16718    /**
16719     * A Property wrapper around the <code>translationY</code> functionality handled by the
16720     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16721     */
16722    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16723        @Override
16724        public void setValue(View object, float value) {
16725            object.setTranslationY(value);
16726        }
16727
16728        @Override
16729        public Float get(View object) {
16730            return object.getTranslationY();
16731        }
16732    };
16733
16734    /**
16735     * A Property wrapper around the <code>x</code> functionality handled by the
16736     * {@link View#setX(float)} and {@link View#getX()} methods.
16737     */
16738    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16739        @Override
16740        public void setValue(View object, float value) {
16741            object.setX(value);
16742        }
16743
16744        @Override
16745        public Float get(View object) {
16746            return object.getX();
16747        }
16748    };
16749
16750    /**
16751     * A Property wrapper around the <code>y</code> functionality handled by the
16752     * {@link View#setY(float)} and {@link View#getY()} methods.
16753     */
16754    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16755        @Override
16756        public void setValue(View object, float value) {
16757            object.setY(value);
16758        }
16759
16760        @Override
16761        public Float get(View object) {
16762            return object.getY();
16763        }
16764    };
16765
16766    /**
16767     * A Property wrapper around the <code>rotation</code> functionality handled by the
16768     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16769     */
16770    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16771        @Override
16772        public void setValue(View object, float value) {
16773            object.setRotation(value);
16774        }
16775
16776        @Override
16777        public Float get(View object) {
16778            return object.getRotation();
16779        }
16780    };
16781
16782    /**
16783     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16784     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16785     */
16786    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16787        @Override
16788        public void setValue(View object, float value) {
16789            object.setRotationX(value);
16790        }
16791
16792        @Override
16793        public Float get(View object) {
16794            return object.getRotationX();
16795        }
16796    };
16797
16798    /**
16799     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16800     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16801     */
16802    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16803        @Override
16804        public void setValue(View object, float value) {
16805            object.setRotationY(value);
16806        }
16807
16808        @Override
16809        public Float get(View object) {
16810            return object.getRotationY();
16811        }
16812    };
16813
16814    /**
16815     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16816     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16817     */
16818    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16819        @Override
16820        public void setValue(View object, float value) {
16821            object.setScaleX(value);
16822        }
16823
16824        @Override
16825        public Float get(View object) {
16826            return object.getScaleX();
16827        }
16828    };
16829
16830    /**
16831     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16832     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16833     */
16834    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16835        @Override
16836        public void setValue(View object, float value) {
16837            object.setScaleY(value);
16838        }
16839
16840        @Override
16841        public Float get(View object) {
16842            return object.getScaleY();
16843        }
16844    };
16845
16846    /**
16847     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16848     * Each MeasureSpec represents a requirement for either the width or the height.
16849     * A MeasureSpec is comprised of a size and a mode. There are three possible
16850     * modes:
16851     * <dl>
16852     * <dt>UNSPECIFIED</dt>
16853     * <dd>
16854     * The parent has not imposed any constraint on the child. It can be whatever size
16855     * it wants.
16856     * </dd>
16857     *
16858     * <dt>EXACTLY</dt>
16859     * <dd>
16860     * The parent has determined an exact size for the child. The child is going to be
16861     * given those bounds regardless of how big it wants to be.
16862     * </dd>
16863     *
16864     * <dt>AT_MOST</dt>
16865     * <dd>
16866     * The child can be as large as it wants up to the specified size.
16867     * </dd>
16868     * </dl>
16869     *
16870     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16871     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16872     */
16873    public static class MeasureSpec {
16874        private static final int MODE_SHIFT = 30;
16875        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16876
16877        /**
16878         * Measure specification mode: The parent has not imposed any constraint
16879         * on the child. It can be whatever size it wants.
16880         */
16881        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16882
16883        /**
16884         * Measure specification mode: The parent has determined an exact size
16885         * for the child. The child is going to be given those bounds regardless
16886         * of how big it wants to be.
16887         */
16888        public static final int EXACTLY     = 1 << MODE_SHIFT;
16889
16890        /**
16891         * Measure specification mode: The child can be as large as it wants up
16892         * to the specified size.
16893         */
16894        public static final int AT_MOST     = 2 << MODE_SHIFT;
16895
16896        /**
16897         * Creates a measure specification based on the supplied size and mode.
16898         *
16899         * The mode must always be one of the following:
16900         * <ul>
16901         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16902         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16903         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16904         * </ul>
16905         *
16906         * @param size the size of the measure specification
16907         * @param mode the mode of the measure specification
16908         * @return the measure specification based on size and mode
16909         */
16910        public static int makeMeasureSpec(int size, int mode) {
16911            return size + mode;
16912        }
16913
16914        /**
16915         * Extracts the mode from the supplied measure specification.
16916         *
16917         * @param measureSpec the measure specification to extract the mode from
16918         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16919         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16920         *         {@link android.view.View.MeasureSpec#EXACTLY}
16921         */
16922        public static int getMode(int measureSpec) {
16923            return (measureSpec & MODE_MASK);
16924        }
16925
16926        /**
16927         * Extracts the size from the supplied measure specification.
16928         *
16929         * @param measureSpec the measure specification to extract the size from
16930         * @return the size in pixels defined in the supplied measure specification
16931         */
16932        public static int getSize(int measureSpec) {
16933            return (measureSpec & ~MODE_MASK);
16934        }
16935
16936        /**
16937         * Returns a String representation of the specified measure
16938         * specification.
16939         *
16940         * @param measureSpec the measure specification to convert to a String
16941         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16942         */
16943        public static String toString(int measureSpec) {
16944            int mode = getMode(measureSpec);
16945            int size = getSize(measureSpec);
16946
16947            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16948
16949            if (mode == UNSPECIFIED)
16950                sb.append("UNSPECIFIED ");
16951            else if (mode == EXACTLY)
16952                sb.append("EXACTLY ");
16953            else if (mode == AT_MOST)
16954                sb.append("AT_MOST ");
16955            else
16956                sb.append(mode).append(" ");
16957
16958            sb.append(size);
16959            return sb.toString();
16960        }
16961    }
16962
16963    class CheckForLongPress implements Runnable {
16964
16965        private int mOriginalWindowAttachCount;
16966
16967        public void run() {
16968            if (isPressed() && (mParent != null)
16969                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16970                if (performLongClick()) {
16971                    mHasPerformedLongPress = true;
16972                }
16973            }
16974        }
16975
16976        public void rememberWindowAttachCount() {
16977            mOriginalWindowAttachCount = mWindowAttachCount;
16978        }
16979    }
16980
16981    private final class CheckForTap implements Runnable {
16982        public void run() {
16983            mPrivateFlags &= ~PREPRESSED;
16984            setPressed(true);
16985            checkForLongClick(ViewConfiguration.getTapTimeout());
16986        }
16987    }
16988
16989    private final class PerformClick implements Runnable {
16990        public void run() {
16991            performClick();
16992        }
16993    }
16994
16995    /** @hide */
16996    public void hackTurnOffWindowResizeAnim(boolean off) {
16997        mAttachInfo.mTurnOffWindowResizeAnim = off;
16998    }
16999
17000    /**
17001     * This method returns a ViewPropertyAnimator object, which can be used to animate
17002     * specific properties on this View.
17003     *
17004     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17005     */
17006    public ViewPropertyAnimator animate() {
17007        if (mAnimator == null) {
17008            mAnimator = new ViewPropertyAnimator(this);
17009        }
17010        return mAnimator;
17011    }
17012
17013    /**
17014     * Interface definition for a callback to be invoked when a hardware key event is
17015     * dispatched to this view. The callback will be invoked before the key event is
17016     * given to the view. This is only useful for hardware keyboards; a software input
17017     * method has no obligation to trigger this listener.
17018     */
17019    public interface OnKeyListener {
17020        /**
17021         * Called when a hardware key is dispatched to a view. This allows listeners to
17022         * get a chance to respond before the target view.
17023         * <p>Key presses in software keyboards will generally NOT trigger this method,
17024         * although some may elect to do so in some situations. Do not assume a
17025         * software input method has to be key-based; even if it is, it may use key presses
17026         * in a different way than you expect, so there is no way to reliably catch soft
17027         * input key presses.
17028         *
17029         * @param v The view the key has been dispatched to.
17030         * @param keyCode The code for the physical key that was pressed
17031         * @param event The KeyEvent object containing full information about
17032         *        the event.
17033         * @return True if the listener has consumed the event, false otherwise.
17034         */
17035        boolean onKey(View v, int keyCode, KeyEvent event);
17036    }
17037
17038    /**
17039     * Interface definition for a callback to be invoked when a touch event is
17040     * dispatched to this view. The callback will be invoked before the touch
17041     * event is given to the view.
17042     */
17043    public interface OnTouchListener {
17044        /**
17045         * Called when a touch event is dispatched to a view. This allows listeners to
17046         * get a chance to respond before the target view.
17047         *
17048         * @param v The view the touch event has been dispatched to.
17049         * @param event The MotionEvent object containing full information about
17050         *        the event.
17051         * @return True if the listener has consumed the event, false otherwise.
17052         */
17053        boolean onTouch(View v, MotionEvent event);
17054    }
17055
17056    /**
17057     * Interface definition for a callback to be invoked when a hover event is
17058     * dispatched to this view. The callback will be invoked before the hover
17059     * event is given to the view.
17060     */
17061    public interface OnHoverListener {
17062        /**
17063         * Called when a hover event is dispatched to a view. This allows listeners to
17064         * get a chance to respond before the target view.
17065         *
17066         * @param v The view the hover event has been dispatched to.
17067         * @param event The MotionEvent object containing full information about
17068         *        the event.
17069         * @return True if the listener has consumed the event, false otherwise.
17070         */
17071        boolean onHover(View v, MotionEvent event);
17072    }
17073
17074    /**
17075     * Interface definition for a callback to be invoked when a generic motion event is
17076     * dispatched to this view. The callback will be invoked before the generic motion
17077     * event is given to the view.
17078     */
17079    public interface OnGenericMotionListener {
17080        /**
17081         * Called when a generic motion event is dispatched to a view. This allows listeners to
17082         * get a chance to respond before the target view.
17083         *
17084         * @param v The view the generic motion event has been dispatched to.
17085         * @param event The MotionEvent object containing full information about
17086         *        the event.
17087         * @return True if the listener has consumed the event, false otherwise.
17088         */
17089        boolean onGenericMotion(View v, MotionEvent event);
17090    }
17091
17092    /**
17093     * Interface definition for a callback to be invoked when a view has been clicked and held.
17094     */
17095    public interface OnLongClickListener {
17096        /**
17097         * Called when a view has been clicked and held.
17098         *
17099         * @param v The view that was clicked and held.
17100         *
17101         * @return true if the callback consumed the long click, false otherwise.
17102         */
17103        boolean onLongClick(View v);
17104    }
17105
17106    /**
17107     * Interface definition for a callback to be invoked when a drag is being dispatched
17108     * to this view.  The callback will be invoked before the hosting view's own
17109     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17110     * onDrag(event) behavior, it should return 'false' from this callback.
17111     *
17112     * <div class="special reference">
17113     * <h3>Developer Guides</h3>
17114     * <p>For a guide to implementing drag and drop features, read the
17115     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17116     * </div>
17117     */
17118    public interface OnDragListener {
17119        /**
17120         * Called when a drag event is dispatched to a view. This allows listeners
17121         * to get a chance to override base View behavior.
17122         *
17123         * @param v The View that received the drag event.
17124         * @param event The {@link android.view.DragEvent} object for the drag event.
17125         * @return {@code true} if the drag event was handled successfully, or {@code false}
17126         * if the drag event was not handled. Note that {@code false} will trigger the View
17127         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17128         */
17129        boolean onDrag(View v, DragEvent event);
17130    }
17131
17132    /**
17133     * Interface definition for a callback to be invoked when the focus state of
17134     * a view changed.
17135     */
17136    public interface OnFocusChangeListener {
17137        /**
17138         * Called when the focus state of a view has changed.
17139         *
17140         * @param v The view whose state has changed.
17141         * @param hasFocus The new focus state of v.
17142         */
17143        void onFocusChange(View v, boolean hasFocus);
17144    }
17145
17146    /**
17147     * Interface definition for a callback to be invoked when a view is clicked.
17148     */
17149    public interface OnClickListener {
17150        /**
17151         * Called when a view has been clicked.
17152         *
17153         * @param v The view that was clicked.
17154         */
17155        void onClick(View v);
17156    }
17157
17158    /**
17159     * Interface definition for a callback to be invoked when the context menu
17160     * for this view is being built.
17161     */
17162    public interface OnCreateContextMenuListener {
17163        /**
17164         * Called when the context menu for this view is being built. It is not
17165         * safe to hold onto the menu after this method returns.
17166         *
17167         * @param menu The context menu that is being built
17168         * @param v The view for which the context menu is being built
17169         * @param menuInfo Extra information about the item for which the
17170         *            context menu should be shown. This information will vary
17171         *            depending on the class of v.
17172         */
17173        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17174    }
17175
17176    /**
17177     * Interface definition for a callback to be invoked when the status bar changes
17178     * visibility.  This reports <strong>global</strong> changes to the system UI
17179     * state, not what the application is requesting.
17180     *
17181     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17182     */
17183    public interface OnSystemUiVisibilityChangeListener {
17184        /**
17185         * Called when the status bar changes visibility because of a call to
17186         * {@link View#setSystemUiVisibility(int)}.
17187         *
17188         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17189         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17190         * This tells you the <strong>global</strong> state of these UI visibility
17191         * flags, not what your app is currently applying.
17192         */
17193        public void onSystemUiVisibilityChange(int visibility);
17194    }
17195
17196    /**
17197     * Interface definition for a callback to be invoked when this view is attached
17198     * or detached from its window.
17199     */
17200    public interface OnAttachStateChangeListener {
17201        /**
17202         * Called when the view is attached to a window.
17203         * @param v The view that was attached
17204         */
17205        public void onViewAttachedToWindow(View v);
17206        /**
17207         * Called when the view is detached from a window.
17208         * @param v The view that was detached
17209         */
17210        public void onViewDetachedFromWindow(View v);
17211    }
17212
17213    private final class UnsetPressedState implements Runnable {
17214        public void run() {
17215            setPressed(false);
17216        }
17217    }
17218
17219    /**
17220     * Base class for derived classes that want to save and restore their own
17221     * state in {@link android.view.View#onSaveInstanceState()}.
17222     */
17223    public static class BaseSavedState extends AbsSavedState {
17224        /**
17225         * Constructor used when reading from a parcel. Reads the state of the superclass.
17226         *
17227         * @param source
17228         */
17229        public BaseSavedState(Parcel source) {
17230            super(source);
17231        }
17232
17233        /**
17234         * Constructor called by derived classes when creating their SavedState objects
17235         *
17236         * @param superState The state of the superclass of this view
17237         */
17238        public BaseSavedState(Parcelable superState) {
17239            super(superState);
17240        }
17241
17242        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17243                new Parcelable.Creator<BaseSavedState>() {
17244            public BaseSavedState createFromParcel(Parcel in) {
17245                return new BaseSavedState(in);
17246            }
17247
17248            public BaseSavedState[] newArray(int size) {
17249                return new BaseSavedState[size];
17250            }
17251        };
17252    }
17253
17254    /**
17255     * A set of information given to a view when it is attached to its parent
17256     * window.
17257     */
17258    static class AttachInfo {
17259        interface Callbacks {
17260            void playSoundEffect(int effectId);
17261            boolean performHapticFeedback(int effectId, boolean always);
17262        }
17263
17264        /**
17265         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17266         * to a Handler. This class contains the target (View) to invalidate and
17267         * the coordinates of the dirty rectangle.
17268         *
17269         * For performance purposes, this class also implements a pool of up to
17270         * POOL_LIMIT objects that get reused. This reduces memory allocations
17271         * whenever possible.
17272         */
17273        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17274            private static final int POOL_LIMIT = 10;
17275            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17276                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17277                        public InvalidateInfo newInstance() {
17278                            return new InvalidateInfo();
17279                        }
17280
17281                        public void onAcquired(InvalidateInfo element) {
17282                        }
17283
17284                        public void onReleased(InvalidateInfo element) {
17285                            element.target = null;
17286                        }
17287                    }, POOL_LIMIT)
17288            );
17289
17290            private InvalidateInfo mNext;
17291            private boolean mIsPooled;
17292
17293            View target;
17294
17295            int left;
17296            int top;
17297            int right;
17298            int bottom;
17299
17300            public void setNextPoolable(InvalidateInfo element) {
17301                mNext = element;
17302            }
17303
17304            public InvalidateInfo getNextPoolable() {
17305                return mNext;
17306            }
17307
17308            static InvalidateInfo acquire() {
17309                return sPool.acquire();
17310            }
17311
17312            void release() {
17313                sPool.release(this);
17314            }
17315
17316            public boolean isPooled() {
17317                return mIsPooled;
17318            }
17319
17320            public void setPooled(boolean isPooled) {
17321                mIsPooled = isPooled;
17322            }
17323        }
17324
17325        final IWindowSession mSession;
17326
17327        final IWindow mWindow;
17328
17329        final IBinder mWindowToken;
17330
17331        final Callbacks mRootCallbacks;
17332
17333        HardwareCanvas mHardwareCanvas;
17334
17335        /**
17336         * The top view of the hierarchy.
17337         */
17338        View mRootView;
17339
17340        IBinder mPanelParentWindowToken;
17341        Surface mSurface;
17342
17343        boolean mHardwareAccelerated;
17344        boolean mHardwareAccelerationRequested;
17345        HardwareRenderer mHardwareRenderer;
17346
17347        boolean mScreenOn;
17348
17349        /**
17350         * Scale factor used by the compatibility mode
17351         */
17352        float mApplicationScale;
17353
17354        /**
17355         * Indicates whether the application is in compatibility mode
17356         */
17357        boolean mScalingRequired;
17358
17359        /**
17360         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17361         */
17362        boolean mTurnOffWindowResizeAnim;
17363
17364        /**
17365         * Left position of this view's window
17366         */
17367        int mWindowLeft;
17368
17369        /**
17370         * Top position of this view's window
17371         */
17372        int mWindowTop;
17373
17374        /**
17375         * Left actual position of this view's window.
17376         *
17377         * TODO: This is a workaround for 6623031. Remove when fixed.
17378         */
17379        int mActualWindowLeft;
17380
17381        /**
17382         * Actual top position of this view's window.
17383         *
17384         * TODO: This is a workaround for 6623031. Remove when fixed.
17385         */
17386        int mActualWindowTop;
17387
17388        /**
17389         * Indicates whether views need to use 32-bit drawing caches
17390         */
17391        boolean mUse32BitDrawingCache;
17392
17393        /**
17394         * For windows that are full-screen but using insets to layout inside
17395         * of the screen decorations, these are the current insets for the
17396         * content of the window.
17397         */
17398        final Rect mContentInsets = new Rect();
17399
17400        /**
17401         * For windows that are full-screen but using insets to layout inside
17402         * of the screen decorations, these are the current insets for the
17403         * actual visible parts of the window.
17404         */
17405        final Rect mVisibleInsets = new Rect();
17406
17407        /**
17408         * The internal insets given by this window.  This value is
17409         * supplied by the client (through
17410         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17411         * be given to the window manager when changed to be used in laying
17412         * out windows behind it.
17413         */
17414        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17415                = new ViewTreeObserver.InternalInsetsInfo();
17416
17417        /**
17418         * All views in the window's hierarchy that serve as scroll containers,
17419         * used to determine if the window can be resized or must be panned
17420         * to adjust for a soft input area.
17421         */
17422        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17423
17424        final KeyEvent.DispatcherState mKeyDispatchState
17425                = new KeyEvent.DispatcherState();
17426
17427        /**
17428         * Indicates whether the view's window currently has the focus.
17429         */
17430        boolean mHasWindowFocus;
17431
17432        /**
17433         * The current visibility of the window.
17434         */
17435        int mWindowVisibility;
17436
17437        /**
17438         * Indicates the time at which drawing started to occur.
17439         */
17440        long mDrawingTime;
17441
17442        /**
17443         * Indicates whether or not ignoring the DIRTY_MASK flags.
17444         */
17445        boolean mIgnoreDirtyState;
17446
17447        /**
17448         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17449         * to avoid clearing that flag prematurely.
17450         */
17451        boolean mSetIgnoreDirtyState = false;
17452
17453        /**
17454         * Indicates whether the view's window is currently in touch mode.
17455         */
17456        boolean mInTouchMode;
17457
17458        /**
17459         * Indicates that ViewAncestor should trigger a global layout change
17460         * the next time it performs a traversal
17461         */
17462        boolean mRecomputeGlobalAttributes;
17463
17464        /**
17465         * Always report new attributes at next traversal.
17466         */
17467        boolean mForceReportNewAttributes;
17468
17469        /**
17470         * Set during a traveral if any views want to keep the screen on.
17471         */
17472        boolean mKeepScreenOn;
17473
17474        /**
17475         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17476         */
17477        int mSystemUiVisibility;
17478
17479        /**
17480         * Hack to force certain system UI visibility flags to be cleared.
17481         */
17482        int mDisabledSystemUiVisibility;
17483
17484        /**
17485         * Last global system UI visibility reported by the window manager.
17486         */
17487        int mGlobalSystemUiVisibility;
17488
17489        /**
17490         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17491         * attached.
17492         */
17493        boolean mHasSystemUiListeners;
17494
17495        /**
17496         * Set if the visibility of any views has changed.
17497         */
17498        boolean mViewVisibilityChanged;
17499
17500        /**
17501         * Set to true if a view has been scrolled.
17502         */
17503        boolean mViewScrollChanged;
17504
17505        /**
17506         * Global to the view hierarchy used as a temporary for dealing with
17507         * x/y points in the transparent region computations.
17508         */
17509        final int[] mTransparentLocation = new int[2];
17510
17511        /**
17512         * Global to the view hierarchy used as a temporary for dealing with
17513         * x/y points in the ViewGroup.invalidateChild implementation.
17514         */
17515        final int[] mInvalidateChildLocation = new int[2];
17516
17517
17518        /**
17519         * Global to the view hierarchy used as a temporary for dealing with
17520         * x/y location when view is transformed.
17521         */
17522        final float[] mTmpTransformLocation = new float[2];
17523
17524        /**
17525         * The view tree observer used to dispatch global events like
17526         * layout, pre-draw, touch mode change, etc.
17527         */
17528        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17529
17530        /**
17531         * A Canvas used by the view hierarchy to perform bitmap caching.
17532         */
17533        Canvas mCanvas;
17534
17535        /**
17536         * The view root impl.
17537         */
17538        final ViewRootImpl mViewRootImpl;
17539
17540        /**
17541         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17542         * handler can be used to pump events in the UI events queue.
17543         */
17544        final Handler mHandler;
17545
17546        /**
17547         * Temporary for use in computing invalidate rectangles while
17548         * calling up the hierarchy.
17549         */
17550        final Rect mTmpInvalRect = new Rect();
17551
17552        /**
17553         * Temporary for use in computing hit areas with transformed views
17554         */
17555        final RectF mTmpTransformRect = new RectF();
17556
17557        /**
17558         * Temporary list for use in collecting focusable descendents of a view.
17559         */
17560        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17561
17562        /**
17563         * The id of the window for accessibility purposes.
17564         */
17565        int mAccessibilityWindowId = View.NO_ID;
17566
17567        /**
17568         * Whether to ingore not exposed for accessibility Views when
17569         * reporting the view tree to accessibility services.
17570         */
17571        boolean mIncludeNotImportantViews;
17572
17573        /**
17574         * The drawable for highlighting accessibility focus.
17575         */
17576        Drawable mAccessibilityFocusDrawable;
17577
17578        /**
17579         * Show where the margins, bounds and layout bounds are for each view.
17580         */
17581        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17582
17583        /**
17584         * Point used to compute visible regions.
17585         */
17586        final Point mPoint = new Point();
17587
17588        /**
17589         * Creates a new set of attachment information with the specified
17590         * events handler and thread.
17591         *
17592         * @param handler the events handler the view must use
17593         */
17594        AttachInfo(IWindowSession session, IWindow window,
17595                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17596            mSession = session;
17597            mWindow = window;
17598            mWindowToken = window.asBinder();
17599            mViewRootImpl = viewRootImpl;
17600            mHandler = handler;
17601            mRootCallbacks = effectPlayer;
17602        }
17603    }
17604
17605    /**
17606     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17607     * is supported. This avoids keeping too many unused fields in most
17608     * instances of View.</p>
17609     */
17610    private static class ScrollabilityCache implements Runnable {
17611
17612        /**
17613         * Scrollbars are not visible
17614         */
17615        public static final int OFF = 0;
17616
17617        /**
17618         * Scrollbars are visible
17619         */
17620        public static final int ON = 1;
17621
17622        /**
17623         * Scrollbars are fading away
17624         */
17625        public static final int FADING = 2;
17626
17627        public boolean fadeScrollBars;
17628
17629        public int fadingEdgeLength;
17630        public int scrollBarDefaultDelayBeforeFade;
17631        public int scrollBarFadeDuration;
17632
17633        public int scrollBarSize;
17634        public ScrollBarDrawable scrollBar;
17635        public float[] interpolatorValues;
17636        public View host;
17637
17638        public final Paint paint;
17639        public final Matrix matrix;
17640        public Shader shader;
17641
17642        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17643
17644        private static final float[] OPAQUE = { 255 };
17645        private static final float[] TRANSPARENT = { 0.0f };
17646
17647        /**
17648         * When fading should start. This time moves into the future every time
17649         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17650         */
17651        public long fadeStartTime;
17652
17653
17654        /**
17655         * The current state of the scrollbars: ON, OFF, or FADING
17656         */
17657        public int state = OFF;
17658
17659        private int mLastColor;
17660
17661        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17662            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17663            scrollBarSize = configuration.getScaledScrollBarSize();
17664            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17665            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17666
17667            paint = new Paint();
17668            matrix = new Matrix();
17669            // use use a height of 1, and then wack the matrix each time we
17670            // actually use it.
17671            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17672
17673            paint.setShader(shader);
17674            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17675            this.host = host;
17676        }
17677
17678        public void setFadeColor(int color) {
17679            if (color != 0 && color != mLastColor) {
17680                mLastColor = color;
17681                color |= 0xFF000000;
17682
17683                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17684                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17685
17686                paint.setShader(shader);
17687                // Restore the default transfer mode (src_over)
17688                paint.setXfermode(null);
17689            }
17690        }
17691
17692        public void run() {
17693            long now = AnimationUtils.currentAnimationTimeMillis();
17694            if (now >= fadeStartTime) {
17695
17696                // the animation fades the scrollbars out by changing
17697                // the opacity (alpha) from fully opaque to fully
17698                // transparent
17699                int nextFrame = (int) now;
17700                int framesCount = 0;
17701
17702                Interpolator interpolator = scrollBarInterpolator;
17703
17704                // Start opaque
17705                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17706
17707                // End transparent
17708                nextFrame += scrollBarFadeDuration;
17709                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17710
17711                state = FADING;
17712
17713                // Kick off the fade animation
17714                host.invalidate(true);
17715            }
17716        }
17717    }
17718
17719    /**
17720     * Resuable callback for sending
17721     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17722     */
17723    private class SendViewScrolledAccessibilityEvent implements Runnable {
17724        public volatile boolean mIsPending;
17725
17726        public void run() {
17727            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17728            mIsPending = false;
17729        }
17730    }
17731
17732    /**
17733     * <p>
17734     * This class represents a delegate that can be registered in a {@link View}
17735     * to enhance accessibility support via composition rather via inheritance.
17736     * It is specifically targeted to widget developers that extend basic View
17737     * classes i.e. classes in package android.view, that would like their
17738     * applications to be backwards compatible.
17739     * </p>
17740     * <div class="special reference">
17741     * <h3>Developer Guides</h3>
17742     * <p>For more information about making applications accessible, read the
17743     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17744     * developer guide.</p>
17745     * </div>
17746     * <p>
17747     * A scenario in which a developer would like to use an accessibility delegate
17748     * is overriding a method introduced in a later API version then the minimal API
17749     * version supported by the application. For example, the method
17750     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17751     * in API version 4 when the accessibility APIs were first introduced. If a
17752     * developer would like his application to run on API version 4 devices (assuming
17753     * all other APIs used by the application are version 4 or lower) and take advantage
17754     * of this method, instead of overriding the method which would break the application's
17755     * backwards compatibility, he can override the corresponding method in this
17756     * delegate and register the delegate in the target View if the API version of
17757     * the system is high enough i.e. the API version is same or higher to the API
17758     * version that introduced
17759     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17760     * </p>
17761     * <p>
17762     * Here is an example implementation:
17763     * </p>
17764     * <code><pre><p>
17765     * if (Build.VERSION.SDK_INT >= 14) {
17766     *     // If the API version is equal of higher than the version in
17767     *     // which onInitializeAccessibilityNodeInfo was introduced we
17768     *     // register a delegate with a customized implementation.
17769     *     View view = findViewById(R.id.view_id);
17770     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17771     *         public void onInitializeAccessibilityNodeInfo(View host,
17772     *                 AccessibilityNodeInfo info) {
17773     *             // Let the default implementation populate the info.
17774     *             super.onInitializeAccessibilityNodeInfo(host, info);
17775     *             // Set some other information.
17776     *             info.setEnabled(host.isEnabled());
17777     *         }
17778     *     });
17779     * }
17780     * </code></pre></p>
17781     * <p>
17782     * This delegate contains methods that correspond to the accessibility methods
17783     * in View. If a delegate has been specified the implementation in View hands
17784     * off handling to the corresponding method in this delegate. The default
17785     * implementation the delegate methods behaves exactly as the corresponding
17786     * method in View for the case of no accessibility delegate been set. Hence,
17787     * to customize the behavior of a View method, clients can override only the
17788     * corresponding delegate method without altering the behavior of the rest
17789     * accessibility related methods of the host view.
17790     * </p>
17791     */
17792    public static class AccessibilityDelegate {
17793
17794        /**
17795         * Sends an accessibility event of the given type. If accessibility is not
17796         * enabled this method has no effect.
17797         * <p>
17798         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17799         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17800         * been set.
17801         * </p>
17802         *
17803         * @param host The View hosting the delegate.
17804         * @param eventType The type of the event to send.
17805         *
17806         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17807         */
17808        public void sendAccessibilityEvent(View host, int eventType) {
17809            host.sendAccessibilityEventInternal(eventType);
17810        }
17811
17812        /**
17813         * Performs the specified accessibility action on the view. For
17814         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17815         * <p>
17816         * The default implementation behaves as
17817         * {@link View#performAccessibilityAction(int, Bundle)
17818         *  View#performAccessibilityAction(int, Bundle)} for the case of
17819         *  no accessibility delegate been set.
17820         * </p>
17821         *
17822         * @param action The action to perform.
17823         * @return Whether the action was performed.
17824         *
17825         * @see View#performAccessibilityAction(int, Bundle)
17826         *      View#performAccessibilityAction(int, Bundle)
17827         */
17828        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17829            return host.performAccessibilityActionInternal(action, args);
17830        }
17831
17832        /**
17833         * Sends an accessibility event. This method behaves exactly as
17834         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17835         * empty {@link AccessibilityEvent} and does not perform a check whether
17836         * accessibility is enabled.
17837         * <p>
17838         * The default implementation behaves as
17839         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17840         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17841         * the case of no accessibility delegate been set.
17842         * </p>
17843         *
17844         * @param host The View hosting the delegate.
17845         * @param event The event to send.
17846         *
17847         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17848         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17849         */
17850        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17851            host.sendAccessibilityEventUncheckedInternal(event);
17852        }
17853
17854        /**
17855         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17856         * to its children for adding their text content to the event.
17857         * <p>
17858         * The default implementation behaves as
17859         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17860         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17861         * the case of no accessibility delegate been set.
17862         * </p>
17863         *
17864         * @param host The View hosting the delegate.
17865         * @param event The event.
17866         * @return True if the event population was completed.
17867         *
17868         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17869         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17870         */
17871        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17872            return host.dispatchPopulateAccessibilityEventInternal(event);
17873        }
17874
17875        /**
17876         * Gives a chance to the host View to populate the accessibility event with its
17877         * text content.
17878         * <p>
17879         * The default implementation behaves as
17880         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17881         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17882         * the case of no accessibility delegate been set.
17883         * </p>
17884         *
17885         * @param host The View hosting the delegate.
17886         * @param event The accessibility event which to populate.
17887         *
17888         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17889         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17890         */
17891        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17892            host.onPopulateAccessibilityEventInternal(event);
17893        }
17894
17895        /**
17896         * Initializes an {@link AccessibilityEvent} with information about the
17897         * the host View which is the event source.
17898         * <p>
17899         * The default implementation behaves as
17900         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17901         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17902         * the case of no accessibility delegate been set.
17903         * </p>
17904         *
17905         * @param host The View hosting the delegate.
17906         * @param event The event to initialize.
17907         *
17908         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17909         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17910         */
17911        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17912            host.onInitializeAccessibilityEventInternal(event);
17913        }
17914
17915        /**
17916         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17917         * <p>
17918         * The default implementation behaves as
17919         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17920         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17921         * the case of no accessibility delegate been set.
17922         * </p>
17923         *
17924         * @param host The View hosting the delegate.
17925         * @param info The instance to initialize.
17926         *
17927         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17928         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17929         */
17930        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17931            host.onInitializeAccessibilityNodeInfoInternal(info);
17932        }
17933
17934        /**
17935         * Called when a child of the host View has requested sending an
17936         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17937         * to augment the event.
17938         * <p>
17939         * The default implementation behaves as
17940         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17941         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17942         * the case of no accessibility delegate been set.
17943         * </p>
17944         *
17945         * @param host The View hosting the delegate.
17946         * @param child The child which requests sending the event.
17947         * @param event The event to be sent.
17948         * @return True if the event should be sent
17949         *
17950         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17951         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17952         */
17953        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17954                AccessibilityEvent event) {
17955            return host.onRequestSendAccessibilityEventInternal(child, event);
17956        }
17957
17958        /**
17959         * Gets the provider for managing a virtual view hierarchy rooted at this View
17960         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17961         * that explore the window content.
17962         * <p>
17963         * The default implementation behaves as
17964         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17965         * the case of no accessibility delegate been set.
17966         * </p>
17967         *
17968         * @return The provider.
17969         *
17970         * @see AccessibilityNodeProvider
17971         */
17972        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17973            return null;
17974        }
17975    }
17976}
17977