View.java revision a9108a217e039492855fbeacda2ab6c4f4a3f70a
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;
93import java.util.concurrent.atomic.AtomicInteger;
94
95/**
96 * <p>
97 * This class represents the basic building block for user interface components. A View
98 * occupies a rectangular area on the screen and is responsible for drawing and
99 * event handling. View is the base class for <em>widgets</em>, which are
100 * used to create interactive UI components (buttons, text fields, etc.). The
101 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
102 * are invisible containers that hold other Views (or other ViewGroups) and define
103 * their layout properties.
104 * </p>
105 *
106 * <div class="special reference">
107 * <h3>Developer Guides</h3>
108 * <p>For information about using this class to develop your application's user interface,
109 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
110 * </div>
111 *
112 * <a name="Using"></a>
113 * <h3>Using Views</h3>
114 * <p>
115 * All of the views in a window are arranged in a single tree. You can add views
116 * either from code or by specifying a tree of views in one or more XML layout
117 * files. There are many specialized subclasses of views that act as controls or
118 * are capable of displaying text, images, or other content.
119 * </p>
120 * <p>
121 * Once you have created a tree of views, there are typically a few types of
122 * common operations you may wish to perform:
123 * <ul>
124 * <li><strong>Set properties:</strong> for example setting the text of a
125 * {@link android.widget.TextView}. The available properties and the methods
126 * that set them will vary among the different subclasses of views. Note that
127 * properties that are known at build time can be set in the XML layout
128 * files.</li>
129 * <li><strong>Set focus:</strong> The framework will handled moving focus in
130 * response to user input. To force focus to a specific view, call
131 * {@link #requestFocus}.</li>
132 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
133 * that will be notified when something interesting happens to the view. For
134 * example, all views will let you set a listener to be notified when the view
135 * gains or loses focus. You can register such a listener using
136 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
137 * Other view subclasses offer more specialized listeners. For example, a Button
138 * exposes a listener to notify clients when the button is clicked.</li>
139 * <li><strong>Set visibility:</strong> You can hide or show views using
140 * {@link #setVisibility(int)}.</li>
141 * </ul>
142 * </p>
143 * <p><em>
144 * Note: The Android framework is responsible for measuring, laying out and
145 * drawing views. You should not call methods that perform these actions on
146 * views yourself unless you are actually implementing a
147 * {@link android.view.ViewGroup}.
148 * </em></p>
149 *
150 * <a name="Lifecycle"></a>
151 * <h3>Implementing a Custom View</h3>
152 *
153 * <p>
154 * To implement a custom view, you will usually begin by providing overrides for
155 * some of the standard methods that the framework calls on all views. You do
156 * not need to override all of these methods. In fact, you can start by just
157 * overriding {@link #onDraw(android.graphics.Canvas)}.
158 * <table border="2" width="85%" align="center" cellpadding="5">
159 *     <thead>
160 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
161 *     </thead>
162 *
163 *     <tbody>
164 *     <tr>
165 *         <td rowspan="2">Creation</td>
166 *         <td>Constructors</td>
167 *         <td>There is a form of the constructor that are called when the view
168 *         is created from code and a form that is called when the view is
169 *         inflated from a layout file. The second form should parse and apply
170 *         any attributes defined in the layout file.
171 *         </td>
172 *     </tr>
173 *     <tr>
174 *         <td><code>{@link #onFinishInflate()}</code></td>
175 *         <td>Called after a view and all of its children has been inflated
176 *         from XML.</td>
177 *     </tr>
178 *
179 *     <tr>
180 *         <td rowspan="3">Layout</td>
181 *         <td><code>{@link #onMeasure(int, int)}</code></td>
182 *         <td>Called to determine the size requirements for this view and all
183 *         of its children.
184 *         </td>
185 *     </tr>
186 *     <tr>
187 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
188 *         <td>Called when this view should assign a size and position to all
189 *         of its children.
190 *         </td>
191 *     </tr>
192 *     <tr>
193 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
194 *         <td>Called when the size of this view has changed.
195 *         </td>
196 *     </tr>
197 *
198 *     <tr>
199 *         <td>Drawing</td>
200 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
201 *         <td>Called when the view should render its content.
202 *         </td>
203 *     </tr>
204 *
205 *     <tr>
206 *         <td rowspan="4">Event processing</td>
207 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
208 *         <td>Called when a new hardware key event occurs.
209 *         </td>
210 *     </tr>
211 *     <tr>
212 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
213 *         <td>Called when a hardware key up event occurs.
214 *         </td>
215 *     </tr>
216 *     <tr>
217 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
218 *         <td>Called when a trackball motion event occurs.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
223 *         <td>Called when a touch screen motion event occurs.
224 *         </td>
225 *     </tr>
226 *
227 *     <tr>
228 *         <td rowspan="2">Focus</td>
229 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
230 *         <td>Called when the view gains or loses focus.
231 *         </td>
232 *     </tr>
233 *
234 *     <tr>
235 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
236 *         <td>Called when the window containing the view gains or loses focus.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td rowspan="3">Attaching</td>
242 *         <td><code>{@link #onAttachedToWindow()}</code></td>
243 *         <td>Called when the view is attached to a window.
244 *         </td>
245 *     </tr>
246 *
247 *     <tr>
248 *         <td><code>{@link #onDetachedFromWindow}</code></td>
249 *         <td>Called when the view is detached from its window.
250 *         </td>
251 *     </tr>
252 *
253 *     <tr>
254 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
255 *         <td>Called when the visibility of the window containing the view
256 *         has changed.
257 *         </td>
258 *     </tr>
259 *     </tbody>
260 *
261 * </table>
262 * </p>
263 *
264 * <a name="IDs"></a>
265 * <h3>IDs</h3>
266 * Views may have an integer id associated with them. These ids are typically
267 * assigned in the layout XML files, and are used to find specific views within
268 * the view tree. A common pattern is to:
269 * <ul>
270 * <li>Define a Button in the layout file and assign it a unique ID.
271 * <pre>
272 * &lt;Button
273 *     android:id="@+id/my_button"
274 *     android:layout_width="wrap_content"
275 *     android:layout_height="wrap_content"
276 *     android:text="@string/my_button_text"/&gt;
277 * </pre></li>
278 * <li>From the onCreate method of an Activity, find the Button
279 * <pre class="prettyprint">
280 *      Button myButton = (Button) findViewById(R.id.my_button);
281 * </pre></li>
282 * </ul>
283 * <p>
284 * View IDs need not be unique throughout the tree, but it is good practice to
285 * ensure that they are at least unique within the part of the tree you are
286 * searching.
287 * </p>
288 *
289 * <a name="Position"></a>
290 * <h3>Position</h3>
291 * <p>
292 * The geometry of a view is that of a rectangle. A view has a location,
293 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
294 * two dimensions, expressed as a width and a height. The unit for location
295 * and dimensions is the pixel.
296 * </p>
297 *
298 * <p>
299 * It is possible to retrieve the location of a view by invoking the methods
300 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
301 * coordinate of the rectangle representing the view. The latter returns the
302 * top, or Y, coordinate of the rectangle representing the view. These methods
303 * both return the location of the view relative to its parent. For instance,
304 * when getLeft() returns 20, that means the view is located 20 pixels to the
305 * right of the left edge of its direct parent.
306 * </p>
307 *
308 * <p>
309 * In addition, several convenience methods are offered to avoid unnecessary
310 * computations, namely {@link #getRight()} and {@link #getBottom()}.
311 * These methods return the coordinates of the right and bottom edges of the
312 * rectangle representing the view. For instance, calling {@link #getRight()}
313 * is similar to the following computation: <code>getLeft() + getWidth()</code>
314 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
315 * </p>
316 *
317 * <a name="SizePaddingMargins"></a>
318 * <h3>Size, padding and margins</h3>
319 * <p>
320 * The size of a view is expressed with a width and a height. A view actually
321 * possess two pairs of width and height values.
322 * </p>
323 *
324 * <p>
325 * The first pair is known as <em>measured width</em> and
326 * <em>measured height</em>. These dimensions define how big a view wants to be
327 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
328 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
329 * and {@link #getMeasuredHeight()}.
330 * </p>
331 *
332 * <p>
333 * The second pair is simply known as <em>width</em> and <em>height</em>, or
334 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
335 * dimensions define the actual size of the view on screen, at drawing time and
336 * after layout. These values may, but do not have to, be different from the
337 * measured width and height. The width and height can be obtained by calling
338 * {@link #getWidth()} and {@link #getHeight()}.
339 * </p>
340 *
341 * <p>
342 * To measure its dimensions, a view takes into account its padding. The padding
343 * is expressed in pixels for the left, top, right and bottom parts of the view.
344 * Padding can be used to offset the content of the view by a specific amount of
345 * pixels. For instance, a left padding of 2 will push the view's content by
346 * 2 pixels to the right of the left edge. Padding can be set using the
347 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
348 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
349 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
350 * {@link #getPaddingEnd()}.
351 * </p>
352 *
353 * <p>
354 * Even though a view can define a padding, it does not provide any support for
355 * margins. However, view groups provide such a support. Refer to
356 * {@link android.view.ViewGroup} and
357 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
358 * </p>
359 *
360 * <a name="Layout"></a>
361 * <h3>Layout</h3>
362 * <p>
363 * Layout is a two pass process: a measure pass and a layout pass. The measuring
364 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
365 * of the view tree. Each view pushes dimension specifications down the tree
366 * during the recursion. At the end of the measure pass, every view has stored
367 * its measurements. The second pass happens in
368 * {@link #layout(int,int,int,int)} and is also top-down. During
369 * this pass each parent is responsible for positioning all of its children
370 * using the sizes computed in the measure pass.
371 * </p>
372 *
373 * <p>
374 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
375 * {@link #getMeasuredHeight()} values must be set, along with those for all of
376 * that view's descendants. A view's measured width and measured height values
377 * must respect the constraints imposed by the view's parents. This guarantees
378 * that at the end of the measure pass, all parents accept all of their
379 * children's measurements. A parent view may call measure() more than once on
380 * its children. For example, the parent may measure each child once with
381 * unspecified dimensions to find out how big they want to be, then call
382 * measure() on them again with actual numbers if the sum of all the children's
383 * unconstrained sizes is too big or too small.
384 * </p>
385 *
386 * <p>
387 * The measure pass uses two classes to communicate dimensions. The
388 * {@link MeasureSpec} class is used by views to tell their parents how they
389 * want to be measured and positioned. The base LayoutParams class just
390 * describes how big the view wants to be for both width and height. For each
391 * dimension, it can specify one of:
392 * <ul>
393 * <li> an exact number
394 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
395 * (minus padding)
396 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
397 * enclose its content (plus padding).
398 * </ul>
399 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
400 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
401 * an X and Y value.
402 * </p>
403 *
404 * <p>
405 * MeasureSpecs are used to push requirements down the tree from parent to
406 * child. A MeasureSpec can be in one of three modes:
407 * <ul>
408 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
409 * of a child view. For example, a LinearLayout may call measure() on its child
410 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
411 * tall the child view wants to be given a width of 240 pixels.
412 * <li>EXACTLY: This is used by the parent to impose an exact size on the
413 * child. The child must use this size, and guarantee that all of its
414 * descendants will fit within this size.
415 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
416 * child. The child must gurantee that it and all of its descendants will fit
417 * within this size.
418 * </ul>
419 * </p>
420 *
421 * <p>
422 * To intiate a layout, call {@link #requestLayout}. This method is typically
423 * called by a view on itself when it believes that is can no longer fit within
424 * its current bounds.
425 * </p>
426 *
427 * <a name="Drawing"></a>
428 * <h3>Drawing</h3>
429 * <p>
430 * Drawing is handled by walking the tree and rendering each view that
431 * intersects the invalid region. Because the tree is traversed in-order,
432 * this means that parents will draw before (i.e., behind) their children, with
433 * siblings drawn in the order they appear in the tree.
434 * If you set a background drawable for a View, then the View will draw it for you
435 * before calling back to its <code>onDraw()</code> method.
436 * </p>
437 *
438 * <p>
439 * Note that the framework will not draw views that are not in the invalid region.
440 * </p>
441 *
442 * <p>
443 * To force a view to draw, call {@link #invalidate()}.
444 * </p>
445 *
446 * <a name="EventHandlingThreading"></a>
447 * <h3>Event Handling and Threading</h3>
448 * <p>
449 * The basic cycle of a view is as follows:
450 * <ol>
451 * <li>An event comes in and is dispatched to the appropriate view. The view
452 * handles the event and notifies any listeners.</li>
453 * <li>If in the course of processing the event, the view's bounds may need
454 * to be changed, the view will call {@link #requestLayout()}.</li>
455 * <li>Similarly, if in the course of processing the event the view's appearance
456 * may need to be changed, the view will call {@link #invalidate()}.</li>
457 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
458 * the framework will take care of measuring, laying out, and drawing the tree
459 * as appropriate.</li>
460 * </ol>
461 * </p>
462 *
463 * <p><em>Note: The entire view tree is single threaded. You must always be on
464 * the UI thread when calling any method on any view.</em>
465 * If you are doing work on other threads and want to update the state of a view
466 * from that thread, you should use a {@link Handler}.
467 * </p>
468 *
469 * <a name="FocusHandling"></a>
470 * <h3>Focus Handling</h3>
471 * <p>
472 * The framework will handle routine focus movement in response to user input.
473 * This includes changing the focus as views are removed or hidden, or as new
474 * views become available. Views indicate their willingness to take focus
475 * through the {@link #isFocusable} method. To change whether a view can take
476 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
477 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
478 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
479 * </p>
480 * <p>
481 * Focus movement is based on an algorithm which finds the nearest neighbor in a
482 * given direction. In rare cases, the default algorithm may not match the
483 * intended behavior of the developer. In these situations, you can provide
484 * explicit overrides by using these XML attributes in the layout file:
485 * <pre>
486 * nextFocusDown
487 * nextFocusLeft
488 * nextFocusRight
489 * nextFocusUp
490 * </pre>
491 * </p>
492 *
493 *
494 * <p>
495 * To get a particular view to take focus, call {@link #requestFocus()}.
496 * </p>
497 *
498 * <a name="TouchMode"></a>
499 * <h3>Touch Mode</h3>
500 * <p>
501 * When a user is navigating a user interface via directional keys such as a D-pad, it is
502 * necessary to give focus to actionable items such as buttons so the user can see
503 * what will take input.  If the device has touch capabilities, however, and the user
504 * begins interacting with the interface by touching it, it is no longer necessary to
505 * always highlight, or give focus to, a particular view.  This motivates a mode
506 * for interaction named 'touch mode'.
507 * </p>
508 * <p>
509 * For a touch capable device, once the user touches the screen, the device
510 * will enter touch mode.  From this point onward, only views for which
511 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
512 * Other views that are touchable, like buttons, will not take focus when touched; they will
513 * only fire the on click listeners.
514 * </p>
515 * <p>
516 * Any time a user hits a directional key, such as a D-pad direction, the view device will
517 * exit touch mode, and find a view to take focus, so that the user may resume interacting
518 * with the user interface without touching the screen again.
519 * </p>
520 * <p>
521 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
522 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
523 * </p>
524 *
525 * <a name="Scrolling"></a>
526 * <h3>Scrolling</h3>
527 * <p>
528 * The framework provides basic support for views that wish to internally
529 * scroll their content. This includes keeping track of the X and Y scroll
530 * offset as well as mechanisms for drawing scrollbars. See
531 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
532 * {@link #awakenScrollBars()} for more details.
533 * </p>
534 *
535 * <a name="Tags"></a>
536 * <h3>Tags</h3>
537 * <p>
538 * Unlike IDs, tags are not used to identify views. Tags are essentially an
539 * extra piece of information that can be associated with a view. They are most
540 * often used as a convenience to store data related to views in the views
541 * themselves rather than by putting them in a separate structure.
542 * </p>
543 *
544 * <a name="Properties"></a>
545 * <h3>Properties</h3>
546 * <p>
547 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
548 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
549 * available both in the {@link Property} form as well as in similarly-named setter/getter
550 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
551 * be used to set persistent state associated with these rendering-related properties on the view.
552 * The properties and methods can also be used in conjunction with
553 * {@link android.animation.Animator Animator}-based animations, described more in the
554 * <a href="#Animation">Animation</a> section.
555 * </p>
556 *
557 * <a name="Animation"></a>
558 * <h3>Animation</h3>
559 * <p>
560 * Starting with Android 3.0, the preferred way of animating views is to use the
561 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
562 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
563 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
564 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
565 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
566 * makes animating these View properties particularly easy and efficient.
567 * </p>
568 * <p>
569 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
570 * You can attach an {@link Animation} object to a view using
571 * {@link #setAnimation(Animation)} or
572 * {@link #startAnimation(Animation)}. The animation can alter the scale,
573 * rotation, translation and alpha of a view over time. If the animation is
574 * attached to a view that has children, the animation will affect the entire
575 * subtree rooted by that node. When an animation is started, the framework will
576 * take care of redrawing the appropriate views until the animation completes.
577 * </p>
578 *
579 * <a name="Security"></a>
580 * <h3>Security</h3>
581 * <p>
582 * Sometimes it is essential that an application be able to verify that an action
583 * is being performed with the full knowledge and consent of the user, such as
584 * granting a permission request, making a purchase or clicking on an advertisement.
585 * Unfortunately, a malicious application could try to spoof the user into
586 * performing these actions, unaware, by concealing the intended purpose of the view.
587 * As a remedy, the framework offers a touch filtering mechanism that can be used to
588 * improve the security of views that provide access to sensitive functionality.
589 * </p><p>
590 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
591 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
592 * will discard touches that are received whenever the view's window is obscured by
593 * another visible window.  As a result, the view will not receive touches whenever a
594 * toast, dialog or other window appears above the view's window.
595 * </p><p>
596 * For more fine-grained control over security, consider overriding the
597 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
598 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
599 * </p>
600 *
601 * @attr ref android.R.styleable#View_alpha
602 * @attr ref android.R.styleable#View_background
603 * @attr ref android.R.styleable#View_clickable
604 * @attr ref android.R.styleable#View_contentDescription
605 * @attr ref android.R.styleable#View_drawingCacheQuality
606 * @attr ref android.R.styleable#View_duplicateParentState
607 * @attr ref android.R.styleable#View_id
608 * @attr ref android.R.styleable#View_requiresFadingEdge
609 * @attr ref android.R.styleable#View_fadeScrollbars
610 * @attr ref android.R.styleable#View_fadingEdgeLength
611 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
612 * @attr ref android.R.styleable#View_fitsSystemWindows
613 * @attr ref android.R.styleable#View_isScrollContainer
614 * @attr ref android.R.styleable#View_focusable
615 * @attr ref android.R.styleable#View_focusableInTouchMode
616 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
617 * @attr ref android.R.styleable#View_keepScreenOn
618 * @attr ref android.R.styleable#View_layerType
619 * @attr ref android.R.styleable#View_longClickable
620 * @attr ref android.R.styleable#View_minHeight
621 * @attr ref android.R.styleable#View_minWidth
622 * @attr ref android.R.styleable#View_nextFocusDown
623 * @attr ref android.R.styleable#View_nextFocusLeft
624 * @attr ref android.R.styleable#View_nextFocusRight
625 * @attr ref android.R.styleable#View_nextFocusUp
626 * @attr ref android.R.styleable#View_onClick
627 * @attr ref android.R.styleable#View_padding
628 * @attr ref android.R.styleable#View_paddingBottom
629 * @attr ref android.R.styleable#View_paddingLeft
630 * @attr ref android.R.styleable#View_paddingRight
631 * @attr ref android.R.styleable#View_paddingTop
632 * @attr ref android.R.styleable#View_paddingStart
633 * @attr ref android.R.styleable#View_paddingEnd
634 * @attr ref android.R.styleable#View_saveEnabled
635 * @attr ref android.R.styleable#View_rotation
636 * @attr ref android.R.styleable#View_rotationX
637 * @attr ref android.R.styleable#View_rotationY
638 * @attr ref android.R.styleable#View_scaleX
639 * @attr ref android.R.styleable#View_scaleY
640 * @attr ref android.R.styleable#View_scrollX
641 * @attr ref android.R.styleable#View_scrollY
642 * @attr ref android.R.styleable#View_scrollbarSize
643 * @attr ref android.R.styleable#View_scrollbarStyle
644 * @attr ref android.R.styleable#View_scrollbars
645 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
646 * @attr ref android.R.styleable#View_scrollbarFadeDuration
647 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
648 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
649 * @attr ref android.R.styleable#View_scrollbarThumbVertical
650 * @attr ref android.R.styleable#View_scrollbarTrackVertical
651 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
652 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
653 * @attr ref android.R.styleable#View_soundEffectsEnabled
654 * @attr ref android.R.styleable#View_tag
655 * @attr ref android.R.styleable#View_textAlignment
656 * @attr ref android.R.styleable#View_transformPivotX
657 * @attr ref android.R.styleable#View_transformPivotY
658 * @attr ref android.R.styleable#View_translationX
659 * @attr ref android.R.styleable#View_translationY
660 * @attr ref android.R.styleable#View_visibility
661 *
662 * @see android.view.ViewGroup
663 */
664public class View implements Drawable.Callback, KeyEvent.Callback,
665        AccessibilityEventSource {
666    private static final boolean DBG = false;
667
668    /**
669     * The logging tag used by this class with android.util.Log.
670     */
671    protected static final String VIEW_LOG_TAG = "View";
672
673    /**
674     * When set to true, apps will draw debugging information about their layouts.
675     *
676     * @hide
677     */
678    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
679
680    /**
681     * Used to mark a View that has no ID.
682     */
683    public static final int NO_ID = -1;
684
685    /**
686     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
687     * calling setFlags.
688     */
689    private static final int NOT_FOCUSABLE = 0x00000000;
690
691    /**
692     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
693     * setFlags.
694     */
695    private static final int FOCUSABLE = 0x00000001;
696
697    /**
698     * Mask for use with setFlags indicating bits used for focus.
699     */
700    private static final int FOCUSABLE_MASK = 0x00000001;
701
702    /**
703     * This view will adjust its padding to fit sytem windows (e.g. status bar)
704     */
705    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
706
707    /**
708     * This view is visible.
709     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
710     * android:visibility}.
711     */
712    public static final int VISIBLE = 0x00000000;
713
714    /**
715     * This view is invisible, but it still takes up space for layout purposes.
716     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
717     * android:visibility}.
718     */
719    public static final int INVISIBLE = 0x00000004;
720
721    /**
722     * This view is invisible, and it doesn't take any space for layout
723     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
724     * android:visibility}.
725     */
726    public static final int GONE = 0x00000008;
727
728    /**
729     * Mask for use with setFlags indicating bits used for visibility.
730     * {@hide}
731     */
732    static final int VISIBILITY_MASK = 0x0000000C;
733
734    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
735
736    /**
737     * This view is enabled. Interpretation varies by subclass.
738     * Use with ENABLED_MASK when calling setFlags.
739     * {@hide}
740     */
741    static final int ENABLED = 0x00000000;
742
743    /**
744     * This view is disabled. Interpretation varies by subclass.
745     * Use with ENABLED_MASK when calling setFlags.
746     * {@hide}
747     */
748    static final int DISABLED = 0x00000020;
749
750   /**
751    * Mask for use with setFlags indicating bits used for indicating whether
752    * this view is enabled
753    * {@hide}
754    */
755    static final int ENABLED_MASK = 0x00000020;
756
757    /**
758     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
759     * called and further optimizations will be performed. It is okay to have
760     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
761     * {@hide}
762     */
763    static final int WILL_NOT_DRAW = 0x00000080;
764
765    /**
766     * Mask for use with setFlags indicating bits used for indicating whether
767     * this view is will draw
768     * {@hide}
769     */
770    static final int DRAW_MASK = 0x00000080;
771
772    /**
773     * <p>This view doesn't show scrollbars.</p>
774     * {@hide}
775     */
776    static final int SCROLLBARS_NONE = 0x00000000;
777
778    /**
779     * <p>This view shows horizontal scrollbars.</p>
780     * {@hide}
781     */
782    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
783
784    /**
785     * <p>This view shows vertical scrollbars.</p>
786     * {@hide}
787     */
788    static final int SCROLLBARS_VERTICAL = 0x00000200;
789
790    /**
791     * <p>Mask for use with setFlags indicating bits used for indicating which
792     * scrollbars are enabled.</p>
793     * {@hide}
794     */
795    static final int SCROLLBARS_MASK = 0x00000300;
796
797    /**
798     * Indicates that the view should filter touches when its window is obscured.
799     * Refer to the class comments for more information about this security feature.
800     * {@hide}
801     */
802    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
803
804    /**
805     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
806     * that they are optional and should be skipped if the window has
807     * requested system UI flags that ignore those insets for layout.
808     */
809    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
810
811    /**
812     * <p>This view doesn't show fading edges.</p>
813     * {@hide}
814     */
815    static final int FADING_EDGE_NONE = 0x00000000;
816
817    /**
818     * <p>This view shows horizontal fading edges.</p>
819     * {@hide}
820     */
821    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
822
823    /**
824     * <p>This view shows vertical fading edges.</p>
825     * {@hide}
826     */
827    static final int FADING_EDGE_VERTICAL = 0x00002000;
828
829    /**
830     * <p>Mask for use with setFlags indicating bits used for indicating which
831     * fading edges are enabled.</p>
832     * {@hide}
833     */
834    static final int FADING_EDGE_MASK = 0x00003000;
835
836    /**
837     * <p>Indicates this view can be clicked. When clickable, a View reacts
838     * to clicks by notifying the OnClickListener.<p>
839     * {@hide}
840     */
841    static final int CLICKABLE = 0x00004000;
842
843    /**
844     * <p>Indicates this view is caching its drawing into a bitmap.</p>
845     * {@hide}
846     */
847    static final int DRAWING_CACHE_ENABLED = 0x00008000;
848
849    /**
850     * <p>Indicates that no icicle should be saved for this view.<p>
851     * {@hide}
852     */
853    static final int SAVE_DISABLED = 0x000010000;
854
855    /**
856     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
857     * property.</p>
858     * {@hide}
859     */
860    static final int SAVE_DISABLED_MASK = 0x000010000;
861
862    /**
863     * <p>Indicates that no drawing cache should ever be created for this view.<p>
864     * {@hide}
865     */
866    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
867
868    /**
869     * <p>Indicates this view can take / keep focus when int touch mode.</p>
870     * {@hide}
871     */
872    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
873
874    /**
875     * <p>Enables low quality mode for the drawing cache.</p>
876     */
877    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
878
879    /**
880     * <p>Enables high quality mode for the drawing cache.</p>
881     */
882    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
883
884    /**
885     * <p>Enables automatic quality mode for the drawing cache.</p>
886     */
887    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
888
889    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
890            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
891    };
892
893    /**
894     * <p>Mask for use with setFlags indicating bits used for the cache
895     * quality property.</p>
896     * {@hide}
897     */
898    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
899
900    /**
901     * <p>
902     * Indicates this view can be long clicked. When long clickable, a View
903     * reacts to long clicks by notifying the OnLongClickListener or showing a
904     * context menu.
905     * </p>
906     * {@hide}
907     */
908    static final int LONG_CLICKABLE = 0x00200000;
909
910    /**
911     * <p>Indicates that this view gets its drawable states from its direct parent
912     * and ignores its original internal states.</p>
913     *
914     * @hide
915     */
916    static final int DUPLICATE_PARENT_STATE = 0x00400000;
917
918    /**
919     * The scrollbar style to display the scrollbars inside the content area,
920     * without increasing the padding. The scrollbars will be overlaid with
921     * translucency on the view's content.
922     */
923    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
924
925    /**
926     * The scrollbar style to display the scrollbars inside the padded area,
927     * increasing the padding of the view. The scrollbars will not overlap the
928     * content area of the view.
929     */
930    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
931
932    /**
933     * The scrollbar style to display the scrollbars at the edge of the view,
934     * without increasing the padding. The scrollbars will be overlaid with
935     * translucency.
936     */
937    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
938
939    /**
940     * The scrollbar style to display the scrollbars at the edge of the view,
941     * increasing the padding of the view. The scrollbars will only overlap the
942     * background, if any.
943     */
944    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
945
946    /**
947     * Mask to check if the scrollbar style is overlay or inset.
948     * {@hide}
949     */
950    static final int SCROLLBARS_INSET_MASK = 0x01000000;
951
952    /**
953     * Mask to check if the scrollbar style is inside or outside.
954     * {@hide}
955     */
956    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
957
958    /**
959     * Mask for scrollbar style.
960     * {@hide}
961     */
962    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
963
964    /**
965     * View flag indicating that the screen should remain on while the
966     * window containing this view is visible to the user.  This effectively
967     * takes care of automatically setting the WindowManager's
968     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
969     */
970    public static final int KEEP_SCREEN_ON = 0x04000000;
971
972    /**
973     * View flag indicating whether this view should have sound effects enabled
974     * for events such as clicking and touching.
975     */
976    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
977
978    /**
979     * View flag indicating whether this view should have haptic feedback
980     * enabled for events such as long presses.
981     */
982    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
983
984    /**
985     * <p>Indicates that the view hierarchy should stop saving state when
986     * it reaches this view.  If state saving is initiated immediately at
987     * the view, it will be allowed.
988     * {@hide}
989     */
990    static final int PARENT_SAVE_DISABLED = 0x20000000;
991
992    /**
993     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
994     * {@hide}
995     */
996    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
997
998    /**
999     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1000     * should add all focusable Views regardless if they are focusable in touch mode.
1001     */
1002    public static final int FOCUSABLES_ALL = 0x00000000;
1003
1004    /**
1005     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1006     * should add only Views focusable in touch mode.
1007     */
1008    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1009
1010    /**
1011     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1012     * item.
1013     */
1014    public static final int FOCUS_BACKWARD = 0x00000001;
1015
1016    /**
1017     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1018     * item.
1019     */
1020    public static final int FOCUS_FORWARD = 0x00000002;
1021
1022    /**
1023     * Use with {@link #focusSearch(int)}. Move focus to the left.
1024     */
1025    public static final int FOCUS_LEFT = 0x00000011;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus up.
1029     */
1030    public static final int FOCUS_UP = 0x00000021;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus to the right.
1034     */
1035    public static final int FOCUS_RIGHT = 0x00000042;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus down.
1039     */
1040    public static final int FOCUS_DOWN = 0x00000082;
1041
1042    /**
1043     * Bits of {@link #getMeasuredWidthAndState()} and
1044     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1045     */
1046    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1047
1048    /**
1049     * Bits of {@link #getMeasuredWidthAndState()} and
1050     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1051     */
1052    public static final int MEASURED_STATE_MASK = 0xff000000;
1053
1054    /**
1055     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1056     * for functions that combine both width and height into a single int,
1057     * such as {@link #getMeasuredState()} and the childState argument of
1058     * {@link #resolveSizeAndState(int, int, int)}.
1059     */
1060    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1061
1062    /**
1063     * Bit of {@link #getMeasuredWidthAndState()} and
1064     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1065     * is smaller that the space the view would like to have.
1066     */
1067    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1068
1069    /**
1070     * Base View state sets
1071     */
1072    // Singles
1073    /**
1074     * Indicates the view has no states set. States are used with
1075     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1076     * view depending on its state.
1077     *
1078     * @see android.graphics.drawable.Drawable
1079     * @see #getDrawableState()
1080     */
1081    protected static final int[] EMPTY_STATE_SET;
1082    /**
1083     * Indicates the view is enabled. States are used with
1084     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1085     * view depending on its state.
1086     *
1087     * @see android.graphics.drawable.Drawable
1088     * @see #getDrawableState()
1089     */
1090    protected static final int[] ENABLED_STATE_SET;
1091    /**
1092     * Indicates the view is focused. States are used with
1093     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1094     * view depending on its state.
1095     *
1096     * @see android.graphics.drawable.Drawable
1097     * @see #getDrawableState()
1098     */
1099    protected static final int[] FOCUSED_STATE_SET;
1100    /**
1101     * Indicates the view is selected. States are used with
1102     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1103     * view depending on its state.
1104     *
1105     * @see android.graphics.drawable.Drawable
1106     * @see #getDrawableState()
1107     */
1108    protected static final int[] SELECTED_STATE_SET;
1109    /**
1110     * Indicates the view is pressed. States are used with
1111     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1112     * view depending on its state.
1113     *
1114     * @see android.graphics.drawable.Drawable
1115     * @see #getDrawableState()
1116     * @hide
1117     */
1118    protected static final int[] PRESSED_STATE_SET;
1119    /**
1120     * Indicates the view's window has focus. States are used with
1121     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1122     * view depending on its state.
1123     *
1124     * @see android.graphics.drawable.Drawable
1125     * @see #getDrawableState()
1126     */
1127    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1128    // Doubles
1129    /**
1130     * Indicates the view is enabled and has the focus.
1131     *
1132     * @see #ENABLED_STATE_SET
1133     * @see #FOCUSED_STATE_SET
1134     */
1135    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1136    /**
1137     * Indicates the view is enabled and selected.
1138     *
1139     * @see #ENABLED_STATE_SET
1140     * @see #SELECTED_STATE_SET
1141     */
1142    protected static final int[] ENABLED_SELECTED_STATE_SET;
1143    /**
1144     * Indicates the view is enabled and that its window has focus.
1145     *
1146     * @see #ENABLED_STATE_SET
1147     * @see #WINDOW_FOCUSED_STATE_SET
1148     */
1149    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1150    /**
1151     * Indicates the view is focused and selected.
1152     *
1153     * @see #FOCUSED_STATE_SET
1154     * @see #SELECTED_STATE_SET
1155     */
1156    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1157    /**
1158     * Indicates the view has the focus and that its window has the focus.
1159     *
1160     * @see #FOCUSED_STATE_SET
1161     * @see #WINDOW_FOCUSED_STATE_SET
1162     */
1163    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1164    /**
1165     * Indicates the view is selected and that its window has the focus.
1166     *
1167     * @see #SELECTED_STATE_SET
1168     * @see #WINDOW_FOCUSED_STATE_SET
1169     */
1170    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1171    // Triples
1172    /**
1173     * Indicates the view is enabled, focused and selected.
1174     *
1175     * @see #ENABLED_STATE_SET
1176     * @see #FOCUSED_STATE_SET
1177     * @see #SELECTED_STATE_SET
1178     */
1179    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1180    /**
1181     * Indicates the view is enabled, focused and its window has the focus.
1182     *
1183     * @see #ENABLED_STATE_SET
1184     * @see #FOCUSED_STATE_SET
1185     * @see #WINDOW_FOCUSED_STATE_SET
1186     */
1187    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1188    /**
1189     * Indicates the view is enabled, selected and its window has the focus.
1190     *
1191     * @see #ENABLED_STATE_SET
1192     * @see #SELECTED_STATE_SET
1193     * @see #WINDOW_FOCUSED_STATE_SET
1194     */
1195    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1196    /**
1197     * Indicates the view is focused, selected and its window has the focus.
1198     *
1199     * @see #FOCUSED_STATE_SET
1200     * @see #SELECTED_STATE_SET
1201     * @see #WINDOW_FOCUSED_STATE_SET
1202     */
1203    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1204    /**
1205     * Indicates the view is enabled, focused, selected and its window
1206     * has the focus.
1207     *
1208     * @see #ENABLED_STATE_SET
1209     * @see #FOCUSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #WINDOW_FOCUSED_STATE_SET
1212     */
1213    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1214    /**
1215     * Indicates the view is pressed and its window has the focus.
1216     *
1217     * @see #PRESSED_STATE_SET
1218     * @see #WINDOW_FOCUSED_STATE_SET
1219     */
1220    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1221    /**
1222     * Indicates the view is pressed and selected.
1223     *
1224     * @see #PRESSED_STATE_SET
1225     * @see #SELECTED_STATE_SET
1226     */
1227    protected static final int[] PRESSED_SELECTED_STATE_SET;
1228    /**
1229     * Indicates the view is pressed, selected and its window has the focus.
1230     *
1231     * @see #PRESSED_STATE_SET
1232     * @see #SELECTED_STATE_SET
1233     * @see #WINDOW_FOCUSED_STATE_SET
1234     */
1235    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1236    /**
1237     * Indicates the view is pressed and focused.
1238     *
1239     * @see #PRESSED_STATE_SET
1240     * @see #FOCUSED_STATE_SET
1241     */
1242    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1243    /**
1244     * Indicates the view is pressed, focused and its window has the focus.
1245     *
1246     * @see #PRESSED_STATE_SET
1247     * @see #FOCUSED_STATE_SET
1248     * @see #WINDOW_FOCUSED_STATE_SET
1249     */
1250    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1251    /**
1252     * Indicates the view is pressed, focused and selected.
1253     *
1254     * @see #PRESSED_STATE_SET
1255     * @see #SELECTED_STATE_SET
1256     * @see #FOCUSED_STATE_SET
1257     */
1258    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1259    /**
1260     * Indicates the view is pressed, focused, selected and its window has the focus.
1261     *
1262     * @see #PRESSED_STATE_SET
1263     * @see #FOCUSED_STATE_SET
1264     * @see #SELECTED_STATE_SET
1265     * @see #WINDOW_FOCUSED_STATE_SET
1266     */
1267    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1268    /**
1269     * Indicates the view is pressed and enabled.
1270     *
1271     * @see #PRESSED_STATE_SET
1272     * @see #ENABLED_STATE_SET
1273     */
1274    protected static final int[] PRESSED_ENABLED_STATE_SET;
1275    /**
1276     * Indicates the view is pressed, enabled and its window has the focus.
1277     *
1278     * @see #PRESSED_STATE_SET
1279     * @see #ENABLED_STATE_SET
1280     * @see #WINDOW_FOCUSED_STATE_SET
1281     */
1282    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1283    /**
1284     * Indicates the view is pressed, enabled and selected.
1285     *
1286     * @see #PRESSED_STATE_SET
1287     * @see #ENABLED_STATE_SET
1288     * @see #SELECTED_STATE_SET
1289     */
1290    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1291    /**
1292     * Indicates the view is pressed, enabled, selected and its window has the
1293     * focus.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #ENABLED_STATE_SET
1297     * @see #SELECTED_STATE_SET
1298     * @see #WINDOW_FOCUSED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, enabled and focused.
1303     *
1304     * @see #PRESSED_STATE_SET
1305     * @see #ENABLED_STATE_SET
1306     * @see #FOCUSED_STATE_SET
1307     */
1308    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1309    /**
1310     * Indicates the view is pressed, enabled, focused and its window has the
1311     * focus.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #ENABLED_STATE_SET
1315     * @see #FOCUSED_STATE_SET
1316     * @see #WINDOW_FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled, focused and selected.
1321     *
1322     * @see #PRESSED_STATE_SET
1323     * @see #ENABLED_STATE_SET
1324     * @see #SELECTED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, enabled, focused, selected and its window
1330     * has the focus.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #ENABLED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     * @see #WINDOW_FOCUSED_STATE_SET
1337     */
1338    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1339
1340    /**
1341     * The order here is very important to {@link #getDrawableState()}
1342     */
1343    private static final int[][] VIEW_STATE_SETS;
1344
1345    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1346    static final int VIEW_STATE_SELECTED = 1 << 1;
1347    static final int VIEW_STATE_FOCUSED = 1 << 2;
1348    static final int VIEW_STATE_ENABLED = 1 << 3;
1349    static final int VIEW_STATE_PRESSED = 1 << 4;
1350    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1351    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1352    static final int VIEW_STATE_HOVERED = 1 << 7;
1353    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1354    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1355
1356    static final int[] VIEW_STATE_IDS = new int[] {
1357        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1358        R.attr.state_selected,          VIEW_STATE_SELECTED,
1359        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1360        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1361        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1362        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1363        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1364        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1365        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1366        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1367    };
1368
1369    static {
1370        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1371            throw new IllegalStateException(
1372                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1373        }
1374        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1375        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1376            int viewState = R.styleable.ViewDrawableStates[i];
1377            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1378                if (VIEW_STATE_IDS[j] == viewState) {
1379                    orderedIds[i * 2] = viewState;
1380                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1381                }
1382            }
1383        }
1384        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1385        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1386        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1387            int numBits = Integer.bitCount(i);
1388            int[] set = new int[numBits];
1389            int pos = 0;
1390            for (int j = 0; j < orderedIds.length; j += 2) {
1391                if ((i & orderedIds[j+1]) != 0) {
1392                    set[pos++] = orderedIds[j];
1393                }
1394            }
1395            VIEW_STATE_SETS[i] = set;
1396        }
1397
1398        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1399        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1400        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1401        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1402                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1403        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1404        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1405                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1406        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1407                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1408        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1410                | VIEW_STATE_FOCUSED];
1411        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1412        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1413                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1414        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1416        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1418                | VIEW_STATE_ENABLED];
1419        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1421        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1423                | VIEW_STATE_ENABLED];
1424        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1426                | VIEW_STATE_ENABLED];
1427        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1428                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1429                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1430
1431        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1432        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1433                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1434        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1436        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1438                | VIEW_STATE_PRESSED];
1439        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1441        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1443                | VIEW_STATE_PRESSED];
1444        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1446                | VIEW_STATE_PRESSED];
1447        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1449                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1450        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1452        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1454                | VIEW_STATE_PRESSED];
1455        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1457                | VIEW_STATE_PRESSED];
1458        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1459                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1460                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1461        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1463                | VIEW_STATE_PRESSED];
1464        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1466                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1467        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1469                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1470        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1472                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1473                | VIEW_STATE_PRESSED];
1474    }
1475
1476    /**
1477     * Accessibility event types that are dispatched for text population.
1478     */
1479    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1480            AccessibilityEvent.TYPE_VIEW_CLICKED
1481            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1482            | AccessibilityEvent.TYPE_VIEW_SELECTED
1483            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1484            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1485            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1486            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1487            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1488            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1489            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1490            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1491
1492    /**
1493     * Temporary Rect currently for use in setBackground().  This will probably
1494     * be extended in the future to hold our own class with more than just
1495     * a Rect. :)
1496     */
1497    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1498
1499    /**
1500     * Map used to store views' tags.
1501     */
1502    private SparseArray<Object> mKeyedTags;
1503
1504    /**
1505     * The next available accessiiblity id.
1506     */
1507    private static int sNextAccessibilityViewId;
1508
1509    /**
1510     * The animation currently associated with this view.
1511     * @hide
1512     */
1513    protected Animation mCurrentAnimation = null;
1514
1515    /**
1516     * Width as measured during measure pass.
1517     * {@hide}
1518     */
1519    @ViewDebug.ExportedProperty(category = "measurement")
1520    int mMeasuredWidth;
1521
1522    /**
1523     * Height as measured during measure pass.
1524     * {@hide}
1525     */
1526    @ViewDebug.ExportedProperty(category = "measurement")
1527    int mMeasuredHeight;
1528
1529    /**
1530     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1531     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1532     * its display list. This flag, used only when hw accelerated, allows us to clear the
1533     * flag while retaining this information until it's needed (at getDisplayList() time and
1534     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1535     *
1536     * {@hide}
1537     */
1538    boolean mRecreateDisplayList = false;
1539
1540    /**
1541     * The view's identifier.
1542     * {@hide}
1543     *
1544     * @see #setId(int)
1545     * @see #getId()
1546     */
1547    @ViewDebug.ExportedProperty(resolveId = true)
1548    int mID = NO_ID;
1549
1550    /**
1551     * The stable ID of this view for accessibility purposes.
1552     */
1553    int mAccessibilityViewId = NO_ID;
1554
1555    /**
1556     * @hide
1557     */
1558    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1559
1560    /**
1561     * The view's tag.
1562     * {@hide}
1563     *
1564     * @see #setTag(Object)
1565     * @see #getTag()
1566     */
1567    protected Object mTag;
1568
1569    // for mPrivateFlags:
1570    /** {@hide} */
1571    static final int WANTS_FOCUS                    = 0x00000001;
1572    /** {@hide} */
1573    static final int FOCUSED                        = 0x00000002;
1574    /** {@hide} */
1575    static final int SELECTED                       = 0x00000004;
1576    /** {@hide} */
1577    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1578    /** {@hide} */
1579    static final int HAS_BOUNDS                     = 0x00000010;
1580    /** {@hide} */
1581    static final int DRAWN                          = 0x00000020;
1582    /**
1583     * When this flag is set, this view is running an animation on behalf of its
1584     * children and should therefore not cancel invalidate requests, even if they
1585     * lie outside of this view's bounds.
1586     *
1587     * {@hide}
1588     */
1589    static final int DRAW_ANIMATION                 = 0x00000040;
1590    /** {@hide} */
1591    static final int SKIP_DRAW                      = 0x00000080;
1592    /** {@hide} */
1593    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1594    /** {@hide} */
1595    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1596    /** {@hide} */
1597    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1598    /** {@hide} */
1599    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1600    /** {@hide} */
1601    static final int FORCE_LAYOUT                   = 0x00001000;
1602    /** {@hide} */
1603    static final int LAYOUT_REQUIRED                = 0x00002000;
1604
1605    private static final int PRESSED                = 0x00004000;
1606
1607    /** {@hide} */
1608    static final int DRAWING_CACHE_VALID            = 0x00008000;
1609    /**
1610     * Flag used to indicate that this view should be drawn once more (and only once
1611     * more) after its animation has completed.
1612     * {@hide}
1613     */
1614    static final int ANIMATION_STARTED              = 0x00010000;
1615
1616    private static final int SAVE_STATE_CALLED      = 0x00020000;
1617
1618    /**
1619     * Indicates that the View returned true when onSetAlpha() was called and that
1620     * the alpha must be restored.
1621     * {@hide}
1622     */
1623    static final int ALPHA_SET                      = 0x00040000;
1624
1625    /**
1626     * Set by {@link #setScrollContainer(boolean)}.
1627     */
1628    static final int SCROLL_CONTAINER               = 0x00080000;
1629
1630    /**
1631     * Set by {@link #setScrollContainer(boolean)}.
1632     */
1633    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1634
1635    /**
1636     * View flag indicating whether this view was invalidated (fully or partially.)
1637     *
1638     * @hide
1639     */
1640    static final int DIRTY                          = 0x00200000;
1641
1642    /**
1643     * View flag indicating whether this view was invalidated by an opaque
1644     * invalidate request.
1645     *
1646     * @hide
1647     */
1648    static final int DIRTY_OPAQUE                   = 0x00400000;
1649
1650    /**
1651     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1652     *
1653     * @hide
1654     */
1655    static final int DIRTY_MASK                     = 0x00600000;
1656
1657    /**
1658     * Indicates whether the background is opaque.
1659     *
1660     * @hide
1661     */
1662    static final int OPAQUE_BACKGROUND              = 0x00800000;
1663
1664    /**
1665     * Indicates whether the scrollbars are opaque.
1666     *
1667     * @hide
1668     */
1669    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1670
1671    /**
1672     * Indicates whether the view is opaque.
1673     *
1674     * @hide
1675     */
1676    static final int OPAQUE_MASK                    = 0x01800000;
1677
1678    /**
1679     * Indicates a prepressed state;
1680     * the short time between ACTION_DOWN and recognizing
1681     * a 'real' press. Prepressed is used to recognize quick taps
1682     * even when they are shorter than ViewConfiguration.getTapTimeout().
1683     *
1684     * @hide
1685     */
1686    private static final int PREPRESSED             = 0x02000000;
1687
1688    /**
1689     * Indicates whether the view is temporarily detached.
1690     *
1691     * @hide
1692     */
1693    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1694
1695    /**
1696     * Indicates that we should awaken scroll bars once attached
1697     *
1698     * @hide
1699     */
1700    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1701
1702    /**
1703     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1704     * @hide
1705     */
1706    private static final int HOVERED              = 0x10000000;
1707
1708    /**
1709     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1710     * for transform operations
1711     *
1712     * @hide
1713     */
1714    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1715
1716    /** {@hide} */
1717    static final int ACTIVATED                    = 0x40000000;
1718
1719    /**
1720     * Indicates that this view was specifically invalidated, not just dirtied because some
1721     * child view was invalidated. The flag is used to determine when we need to recreate
1722     * a view's display list (as opposed to just returning a reference to its existing
1723     * display list).
1724     *
1725     * @hide
1726     */
1727    static final int INVALIDATED                  = 0x80000000;
1728
1729    /* Masks for mPrivateFlags2 */
1730
1731    /**
1732     * Indicates that this view has reported that it can accept the current drag's content.
1733     * Cleared when the drag operation concludes.
1734     * @hide
1735     */
1736    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1737
1738    /**
1739     * Indicates that this view is currently directly under the drag location in a
1740     * drag-and-drop operation involving content that it can accept.  Cleared when
1741     * the drag exits the view, or when the drag operation concludes.
1742     * @hide
1743     */
1744    static final int DRAG_HOVERED                 = 0x00000002;
1745
1746    /**
1747     * Horizontal layout direction of this view is from Left to Right.
1748     * Use with {@link #setLayoutDirection}.
1749     */
1750    public static final int LAYOUT_DIRECTION_LTR = 0;
1751
1752    /**
1753     * Horizontal layout direction of this view is from Right to Left.
1754     * Use with {@link #setLayoutDirection}.
1755     */
1756    public static final int LAYOUT_DIRECTION_RTL = 1;
1757
1758    /**
1759     * Horizontal layout direction of this view is inherited from its parent.
1760     * Use with {@link #setLayoutDirection}.
1761     */
1762    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1763
1764    /**
1765     * Horizontal layout direction of this view is from deduced from the default language
1766     * script for the locale. Use with {@link #setLayoutDirection}.
1767     */
1768    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1769
1770    /**
1771     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1772     * @hide
1773     */
1774    static final int LAYOUT_DIRECTION_MASK_SHIFT = 2;
1775
1776    /**
1777     * Mask for use with private flags indicating bits used for horizontal layout direction.
1778     * @hide
1779     */
1780    static final int LAYOUT_DIRECTION_MASK = 0x00000003 << LAYOUT_DIRECTION_MASK_SHIFT;
1781
1782    /**
1783     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1784     * right-to-left direction.
1785     * @hide
1786     */
1787    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 4 << LAYOUT_DIRECTION_MASK_SHIFT;
1788
1789    /**
1790     * Indicates whether the view horizontal layout direction has been resolved.
1791     * @hide
1792     */
1793    static final int LAYOUT_DIRECTION_RESOLVED = 8 << LAYOUT_DIRECTION_MASK_SHIFT;
1794
1795    /**
1796     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1797     * @hide
1798     */
1799    static final int LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C << LAYOUT_DIRECTION_MASK_SHIFT;
1800
1801    /*
1802     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1803     * flag value.
1804     * @hide
1805     */
1806    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1807            LAYOUT_DIRECTION_LTR,
1808            LAYOUT_DIRECTION_RTL,
1809            LAYOUT_DIRECTION_INHERIT,
1810            LAYOUT_DIRECTION_LOCALE
1811    };
1812
1813    /**
1814     * Default horizontal layout direction.
1815     * @hide
1816     */
1817    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1818
1819    /**
1820     * Indicates that the view is tracking some sort of transient state
1821     * that the app should not need to be aware of, but that the framework
1822     * should take special care to preserve.
1823     *
1824     * @hide
1825     */
1826    static final int HAS_TRANSIENT_STATE = 0x00000100;
1827
1828
1829    /**
1830     * Text direction is inherited thru {@link ViewGroup}
1831     */
1832    public static final int TEXT_DIRECTION_INHERIT = 0;
1833
1834    /**
1835     * Text direction is using "first strong algorithm". The first strong directional character
1836     * determines the paragraph direction. If there is no strong directional character, the
1837     * paragraph direction is the view's resolved layout direction.
1838     */
1839    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1840
1841    /**
1842     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1843     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1844     * If there are neither, the paragraph direction is the view's resolved layout direction.
1845     */
1846    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1847
1848    /**
1849     * Text direction is forced to LTR.
1850     */
1851    public static final int TEXT_DIRECTION_LTR = 3;
1852
1853    /**
1854     * Text direction is forced to RTL.
1855     */
1856    public static final int TEXT_DIRECTION_RTL = 4;
1857
1858    /**
1859     * Text direction is coming from the system Locale.
1860     */
1861    public static final int TEXT_DIRECTION_LOCALE = 5;
1862
1863    /**
1864     * Default text direction is inherited
1865     */
1866    protected static int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1867
1868    /**
1869     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1870     * @hide
1871     */
1872    static final int TEXT_DIRECTION_MASK_SHIFT = 6;
1873
1874    /**
1875     * Mask for use with private flags indicating bits used for text direction.
1876     * @hide
1877     */
1878    static final int TEXT_DIRECTION_MASK = 0x00000007 << TEXT_DIRECTION_MASK_SHIFT;
1879
1880    /**
1881     * Array of text direction flags for mapping attribute "textDirection" to correct
1882     * flag value.
1883     * @hide
1884     */
1885    private static final int[] TEXT_DIRECTION_FLAGS = {
1886            TEXT_DIRECTION_INHERIT << TEXT_DIRECTION_MASK_SHIFT,
1887            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_MASK_SHIFT,
1888            TEXT_DIRECTION_ANY_RTL << TEXT_DIRECTION_MASK_SHIFT,
1889            TEXT_DIRECTION_LTR << TEXT_DIRECTION_MASK_SHIFT,
1890            TEXT_DIRECTION_RTL << TEXT_DIRECTION_MASK_SHIFT,
1891            TEXT_DIRECTION_LOCALE << TEXT_DIRECTION_MASK_SHIFT
1892    };
1893
1894    /**
1895     * Indicates whether the view text direction has been resolved.
1896     * @hide
1897     */
1898    static final int TEXT_DIRECTION_RESOLVED = 0x00000008 << TEXT_DIRECTION_MASK_SHIFT;
1899
1900    /**
1901     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1902     * @hide
1903     */
1904    static final int TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1905
1906    /**
1907     * Mask for use with private flags indicating bits used for resolved text direction.
1908     * @hide
1909     */
1910    static final int TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1911
1912    /**
1913     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1914     * @hide
1915     */
1916    static final int TEXT_DIRECTION_RESOLVED_DEFAULT =
1917            TEXT_DIRECTION_FIRST_STRONG << TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1918
1919    /*
1920     * Default text alignment. The text alignment of this View is inherited from its parent.
1921     * Use with {@link #setTextAlignment(int)}
1922     */
1923    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1924
1925    /**
1926     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1927     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1928     *
1929     * Use with {@link #setTextAlignment(int)}
1930     */
1931    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1932
1933    /**
1934     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1935     *
1936     * Use with {@link #setTextAlignment(int)}
1937     */
1938    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
1939
1940    /**
1941     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
1942     *
1943     * Use with {@link #setTextAlignment(int)}
1944     */
1945    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
1946
1947    /**
1948     * Center the paragraph, e.g. ALIGN_CENTER.
1949     *
1950     * Use with {@link #setTextAlignment(int)}
1951     */
1952    public static final int TEXT_ALIGNMENT_CENTER = 4;
1953
1954    /**
1955     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
1956     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
1957     *
1958     * Use with {@link #setTextAlignment(int)}
1959     */
1960    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
1961
1962    /**
1963     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
1964     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
1965     *
1966     * Use with {@link #setTextAlignment(int)}
1967     */
1968    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
1969
1970    /**
1971     * Default text alignment is inherited
1972     */
1973    protected static int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
1974
1975    /**
1976      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1977      * @hide
1978      */
1979    static final int TEXT_ALIGNMENT_MASK_SHIFT = 13;
1980
1981    /**
1982      * Mask for use with private flags indicating bits used for text alignment.
1983      * @hide
1984      */
1985    static final int TEXT_ALIGNMENT_MASK = 0x00000007 << TEXT_ALIGNMENT_MASK_SHIFT;
1986
1987    /**
1988     * Array of text direction flags for mapping attribute "textAlignment" to correct
1989     * flag value.
1990     * @hide
1991     */
1992    private static final int[] TEXT_ALIGNMENT_FLAGS = {
1993            TEXT_ALIGNMENT_INHERIT << TEXT_ALIGNMENT_MASK_SHIFT,
1994            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_MASK_SHIFT,
1995            TEXT_ALIGNMENT_TEXT_START << TEXT_ALIGNMENT_MASK_SHIFT,
1996            TEXT_ALIGNMENT_TEXT_END << TEXT_ALIGNMENT_MASK_SHIFT,
1997            TEXT_ALIGNMENT_CENTER << TEXT_ALIGNMENT_MASK_SHIFT,
1998            TEXT_ALIGNMENT_VIEW_START << TEXT_ALIGNMENT_MASK_SHIFT,
1999            TEXT_ALIGNMENT_VIEW_END << TEXT_ALIGNMENT_MASK_SHIFT
2000    };
2001
2002    /**
2003     * Indicates whether the view text alignment has been resolved.
2004     * @hide
2005     */
2006    static final int TEXT_ALIGNMENT_RESOLVED = 0x00000008 << TEXT_ALIGNMENT_MASK_SHIFT;
2007
2008    /**
2009     * Bit shift to get the resolved text alignment.
2010     * @hide
2011     */
2012    static final int TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2013
2014    /**
2015     * Mask for use with private flags indicating bits used for text alignment.
2016     * @hide
2017     */
2018    static final int TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2019
2020    /**
2021     * Indicates whether if the view text alignment has been resolved to gravity
2022     */
2023    public static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2024            TEXT_ALIGNMENT_GRAVITY << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2025
2026    // Accessiblity constants for mPrivateFlags2
2027
2028    /**
2029     * Shift for the bits in {@link #mPrivateFlags2} related to the
2030     * "importantForAccessibility" attribute.
2031     */
2032    static final int IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2033
2034    /**
2035     * Automatically determine whether a view is important for accessibility.
2036     */
2037    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2038
2039    /**
2040     * The view is important for accessibility.
2041     */
2042    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2043
2044    /**
2045     * The view is not important for accessibility.
2046     */
2047    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2048
2049    /**
2050     * The default whether the view is important for accessiblity.
2051     */
2052    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2053
2054    /**
2055     * Mask for obtainig the bits which specify how to determine
2056     * whether a view is important for accessibility.
2057     */
2058    static final int IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2059        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2060        << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2061
2062    /**
2063     * Flag indicating whether a view has accessibility focus.
2064     */
2065    static final int ACCESSIBILITY_FOCUSED = 0x00000040 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2066
2067    /**
2068     * Flag indicating whether a view state for accessibility has changed.
2069     */
2070    static final int ACCESSIBILITY_STATE_CHANGED = 0x00000080 << IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2071
2072    /**
2073     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2074     * is used to check whether later changes to the view's transform should invalidate the
2075     * view to force the quickReject test to run again.
2076     */
2077    static final int VIEW_QUICK_REJECTED = 0x10000000;
2078
2079    // There are a couple of flags left in mPrivateFlags2
2080
2081    /* End of masks for mPrivateFlags2 */
2082
2083    /* Masks for mPrivateFlags3 */
2084
2085    /**
2086     * Flag indicating that view has a transform animation set on it. This is used to track whether
2087     * an animation is cleared between successive frames, in order to tell the associated
2088     * DisplayList to clear its animation matrix.
2089     */
2090    static final int VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2091
2092    /**
2093     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2094     * animation is cleared between successive frames, in order to tell the associated
2095     * DisplayList to restore its alpha value.
2096     */
2097    static final int VIEW_IS_ANIMATING_ALPHA = 0x2;
2098
2099
2100    /* End of masks for mPrivateFlags3 */
2101
2102    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
2103
2104    /**
2105     * Always allow a user to over-scroll this view, provided it is a
2106     * view that can scroll.
2107     *
2108     * @see #getOverScrollMode()
2109     * @see #setOverScrollMode(int)
2110     */
2111    public static final int OVER_SCROLL_ALWAYS = 0;
2112
2113    /**
2114     * Allow a user to over-scroll this view only if the content is large
2115     * enough to meaningfully scroll, provided it is a view that can scroll.
2116     *
2117     * @see #getOverScrollMode()
2118     * @see #setOverScrollMode(int)
2119     */
2120    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2121
2122    /**
2123     * Never allow a user to over-scroll this view.
2124     *
2125     * @see #getOverScrollMode()
2126     * @see #setOverScrollMode(int)
2127     */
2128    public static final int OVER_SCROLL_NEVER = 2;
2129
2130    /**
2131     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2132     * requested the system UI (status bar) to be visible (the default).
2133     *
2134     * @see #setSystemUiVisibility(int)
2135     */
2136    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2137
2138    /**
2139     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2140     * system UI to enter an unobtrusive "low profile" mode.
2141     *
2142     * <p>This is for use in games, book readers, video players, or any other
2143     * "immersive" application where the usual system chrome is deemed too distracting.
2144     *
2145     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2146     *
2147     * @see #setSystemUiVisibility(int)
2148     */
2149    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2150
2151    /**
2152     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2153     * system navigation be temporarily hidden.
2154     *
2155     * <p>This is an even less obtrusive state than that called for by
2156     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2157     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2158     * those to disappear. This is useful (in conjunction with the
2159     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2160     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2161     * window flags) for displaying content using every last pixel on the display.
2162     *
2163     * <p>There is a limitation: because navigation controls are so important, the least user
2164     * interaction will cause them to reappear immediately.  When this happens, both
2165     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2166     * so that both elements reappear at the same time.
2167     *
2168     * @see #setSystemUiVisibility(int)
2169     */
2170    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2171
2172    /**
2173     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2174     * into the normal fullscreen mode so that its content can take over the screen
2175     * while still allowing the user to interact with the application.
2176     *
2177     * <p>This has the same visual effect as
2178     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2179     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2180     * meaning that non-critical screen decorations (such as the status bar) will be
2181     * hidden while the user is in the View's window, focusing the experience on
2182     * that content.  Unlike the window flag, if you are using ActionBar in
2183     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2184     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2185     * hide the action bar.
2186     *
2187     * <p>This approach to going fullscreen is best used over the window flag when
2188     * it is a transient state -- that is, the application does this at certain
2189     * points in its user interaction where it wants to allow the user to focus
2190     * on content, but not as a continuous state.  For situations where the application
2191     * would like to simply stay full screen the entire time (such as a game that
2192     * wants to take over the screen), the
2193     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2194     * is usually a better approach.  The state set here will be removed by the system
2195     * in various situations (such as the user moving to another application) like
2196     * the other system UI states.
2197     *
2198     * <p>When using this flag, the application should provide some easy facility
2199     * for the user to go out of it.  A common example would be in an e-book
2200     * reader, where tapping on the screen brings back whatever screen and UI
2201     * decorations that had been hidden while the user was immersed in reading
2202     * the book.
2203     *
2204     * @see #setSystemUiVisibility(int)
2205     */
2206    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2207
2208    /**
2209     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2210     * flags, we would like a stable view of the content insets given to
2211     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2212     * will always represent the worst case that the application can expect
2213     * as a continuous state.  In the stock Android UI this is the space for
2214     * the system bar, nav bar, and status bar, but not more transient elements
2215     * such as an input method.
2216     *
2217     * The stable layout your UI sees is based on the system UI modes you can
2218     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2219     * then you will get a stable layout for changes of the
2220     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2221     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2222     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2223     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2224     * with a stable layout.  (Note that you should avoid using
2225     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2226     *
2227     * If you have set the window flag {@ WindowManager.LayoutParams#FLAG_FULLSCREEN}
2228     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2229     * then a hidden status bar will be considered a "stable" state for purposes
2230     * here.  This allows your UI to continually hide the status bar, while still
2231     * using the system UI flags to hide the action bar while still retaining
2232     * a stable layout.  Note that changing the window fullscreen flag will never
2233     * provide a stable layout for a clean transition.
2234     *
2235     * <p>If you are using ActionBar in
2236     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2237     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2238     * insets it adds to those given to the application.
2239     */
2240    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2241
2242    /**
2243     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2244     * to be layed out as if it has requested
2245     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2246     * allows it to avoid artifacts when switching in and out of that mode, at
2247     * the expense that some of its user interface may be covered by screen
2248     * decorations when they are shown.  You can perform layout of your inner
2249     * UI elements to account for the navagation system UI through the
2250     * {@link #fitSystemWindows(Rect)} method.
2251     */
2252    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2253
2254    /**
2255     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2256     * to be layed out as if it has requested
2257     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2258     * allows it to avoid artifacts when switching in and out of that mode, at
2259     * the expense that some of its user interface may be covered by screen
2260     * decorations when they are shown.  You can perform layout of your inner
2261     * UI elements to account for non-fullscreen system UI through the
2262     * {@link #fitSystemWindows(Rect)} method.
2263     */
2264    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2265
2266    /**
2267     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2268     */
2269    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2270
2271    /**
2272     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2273     */
2274    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2275
2276    /**
2277     * @hide
2278     *
2279     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2280     * out of the public fields to keep the undefined bits out of the developer's way.
2281     *
2282     * Flag to make the status bar not expandable.  Unless you also
2283     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2284     */
2285    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2286
2287    /**
2288     * @hide
2289     *
2290     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2291     * out of the public fields to keep the undefined bits out of the developer's way.
2292     *
2293     * Flag to hide notification icons and scrolling ticker text.
2294     */
2295    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2296
2297    /**
2298     * @hide
2299     *
2300     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2301     * out of the public fields to keep the undefined bits out of the developer's way.
2302     *
2303     * Flag to disable incoming notification alerts.  This will not block
2304     * icons, but it will block sound, vibrating and other visual or aural notifications.
2305     */
2306    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2307
2308    /**
2309     * @hide
2310     *
2311     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2312     * out of the public fields to keep the undefined bits out of the developer's way.
2313     *
2314     * Flag to hide only the scrolling ticker.  Note that
2315     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2316     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2317     */
2318    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2319
2320    /**
2321     * @hide
2322     *
2323     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2324     * out of the public fields to keep the undefined bits out of the developer's way.
2325     *
2326     * Flag to hide the center system info area.
2327     */
2328    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2329
2330    /**
2331     * @hide
2332     *
2333     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2334     * out of the public fields to keep the undefined bits out of the developer's way.
2335     *
2336     * Flag to hide only the home button.  Don't use this
2337     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2338     */
2339    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2340
2341    /**
2342     * @hide
2343     *
2344     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2345     * out of the public fields to keep the undefined bits out of the developer's way.
2346     *
2347     * Flag to hide only the back button. Don't use this
2348     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2349     */
2350    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2351
2352    /**
2353     * @hide
2354     *
2355     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2356     * out of the public fields to keep the undefined bits out of the developer's way.
2357     *
2358     * Flag to hide only the clock.  You might use this if your activity has
2359     * its own clock making the status bar's clock redundant.
2360     */
2361    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2362
2363    /**
2364     * @hide
2365     *
2366     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2367     * out of the public fields to keep the undefined bits out of the developer's way.
2368     *
2369     * Flag to hide only the recent apps button. Don't use this
2370     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2371     */
2372    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2373
2374    /**
2375     * @hide
2376     */
2377    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2378
2379    /**
2380     * These are the system UI flags that can be cleared by events outside
2381     * of an application.  Currently this is just the ability to tap on the
2382     * screen while hiding the navigation bar to have it return.
2383     * @hide
2384     */
2385    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2386            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2387            | SYSTEM_UI_FLAG_FULLSCREEN;
2388
2389    /**
2390     * Flags that can impact the layout in relation to system UI.
2391     */
2392    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2393            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2394            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2395
2396    /**
2397     * Find views that render the specified text.
2398     *
2399     * @see #findViewsWithText(ArrayList, CharSequence, int)
2400     */
2401    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2402
2403    /**
2404     * Find find views that contain the specified content description.
2405     *
2406     * @see #findViewsWithText(ArrayList, CharSequence, int)
2407     */
2408    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2409
2410    /**
2411     * Find views that contain {@link AccessibilityNodeProvider}. Such
2412     * a View is a root of virtual view hierarchy and may contain the searched
2413     * text. If this flag is set Views with providers are automatically
2414     * added and it is a responsibility of the client to call the APIs of
2415     * the provider to determine whether the virtual tree rooted at this View
2416     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2417     * represeting the virtual views with this text.
2418     *
2419     * @see #findViewsWithText(ArrayList, CharSequence, int)
2420     *
2421     * @hide
2422     */
2423    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2424
2425    /**
2426     * The undefined cursor position.
2427     */
2428    private static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2429
2430    /**
2431     * Indicates that the screen has changed state and is now off.
2432     *
2433     * @see #onScreenStateChanged(int)
2434     */
2435    public static final int SCREEN_STATE_OFF = 0x0;
2436
2437    /**
2438     * Indicates that the screen has changed state and is now on.
2439     *
2440     * @see #onScreenStateChanged(int)
2441     */
2442    public static final int SCREEN_STATE_ON = 0x1;
2443
2444    /**
2445     * Controls the over-scroll mode for this view.
2446     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2447     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2448     * and {@link #OVER_SCROLL_NEVER}.
2449     */
2450    private int mOverScrollMode;
2451
2452    /**
2453     * The parent this view is attached to.
2454     * {@hide}
2455     *
2456     * @see #getParent()
2457     */
2458    protected ViewParent mParent;
2459
2460    /**
2461     * {@hide}
2462     */
2463    AttachInfo mAttachInfo;
2464
2465    /**
2466     * {@hide}
2467     */
2468    @ViewDebug.ExportedProperty(flagMapping = {
2469        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2470                name = "FORCE_LAYOUT"),
2471        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2472                name = "LAYOUT_REQUIRED"),
2473        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2474            name = "DRAWING_CACHE_INVALID", outputIf = false),
2475        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2476        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2477        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2478        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2479    })
2480    int mPrivateFlags;
2481    int mPrivateFlags2;
2482    int mPrivateFlags3;
2483
2484    /**
2485     * This view's request for the visibility of the status bar.
2486     * @hide
2487     */
2488    @ViewDebug.ExportedProperty(flagMapping = {
2489        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2490                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2491                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2492        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2493                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2494                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2495        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2496                                equals = SYSTEM_UI_FLAG_VISIBLE,
2497                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2498    })
2499    int mSystemUiVisibility;
2500
2501    /**
2502     * Reference count for transient state.
2503     * @see #setHasTransientState(boolean)
2504     */
2505    int mTransientStateCount = 0;
2506
2507    /**
2508     * Count of how many windows this view has been attached to.
2509     */
2510    int mWindowAttachCount;
2511
2512    /**
2513     * The layout parameters associated with this view and used by the parent
2514     * {@link android.view.ViewGroup} to determine how this view should be
2515     * laid out.
2516     * {@hide}
2517     */
2518    protected ViewGroup.LayoutParams mLayoutParams;
2519
2520    /**
2521     * The view flags hold various views states.
2522     * {@hide}
2523     */
2524    @ViewDebug.ExportedProperty
2525    int mViewFlags;
2526
2527    static class TransformationInfo {
2528        /**
2529         * The transform matrix for the View. This transform is calculated internally
2530         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2531         * is used by default. Do *not* use this variable directly; instead call
2532         * getMatrix(), which will automatically recalculate the matrix if necessary
2533         * to get the correct matrix based on the latest rotation and scale properties.
2534         */
2535        private final Matrix mMatrix = new Matrix();
2536
2537        /**
2538         * The transform matrix for the View. This transform is calculated internally
2539         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2540         * is used by default. Do *not* use this variable directly; instead call
2541         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2542         * to get the correct matrix based on the latest rotation and scale properties.
2543         */
2544        private Matrix mInverseMatrix;
2545
2546        /**
2547         * An internal variable that tracks whether we need to recalculate the
2548         * transform matrix, based on whether the rotation or scaleX/Y properties
2549         * have changed since the matrix was last calculated.
2550         */
2551        boolean mMatrixDirty = false;
2552
2553        /**
2554         * An internal variable that tracks whether we need to recalculate the
2555         * transform matrix, based on whether the rotation or scaleX/Y properties
2556         * have changed since the matrix was last calculated.
2557         */
2558        private boolean mInverseMatrixDirty = true;
2559
2560        /**
2561         * A variable that tracks whether we need to recalculate the
2562         * transform matrix, based on whether the rotation or scaleX/Y properties
2563         * have changed since the matrix was last calculated. This variable
2564         * is only valid after a call to updateMatrix() or to a function that
2565         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2566         */
2567        private boolean mMatrixIsIdentity = true;
2568
2569        /**
2570         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2571         */
2572        private Camera mCamera = null;
2573
2574        /**
2575         * This matrix is used when computing the matrix for 3D rotations.
2576         */
2577        private Matrix matrix3D = null;
2578
2579        /**
2580         * These prev values are used to recalculate a centered pivot point when necessary. The
2581         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2582         * set), so thes values are only used then as well.
2583         */
2584        private int mPrevWidth = -1;
2585        private int mPrevHeight = -1;
2586
2587        /**
2588         * The degrees rotation around the vertical axis through the pivot point.
2589         */
2590        @ViewDebug.ExportedProperty
2591        float mRotationY = 0f;
2592
2593        /**
2594         * The degrees rotation around the horizontal axis through the pivot point.
2595         */
2596        @ViewDebug.ExportedProperty
2597        float mRotationX = 0f;
2598
2599        /**
2600         * The degrees rotation around the pivot point.
2601         */
2602        @ViewDebug.ExportedProperty
2603        float mRotation = 0f;
2604
2605        /**
2606         * The amount of translation of the object away from its left property (post-layout).
2607         */
2608        @ViewDebug.ExportedProperty
2609        float mTranslationX = 0f;
2610
2611        /**
2612         * The amount of translation of the object away from its top property (post-layout).
2613         */
2614        @ViewDebug.ExportedProperty
2615        float mTranslationY = 0f;
2616
2617        /**
2618         * The amount of scale in the x direction around the pivot point. A
2619         * value of 1 means no scaling is applied.
2620         */
2621        @ViewDebug.ExportedProperty
2622        float mScaleX = 1f;
2623
2624        /**
2625         * The amount of scale in the y direction around the pivot point. A
2626         * value of 1 means no scaling is applied.
2627         */
2628        @ViewDebug.ExportedProperty
2629        float mScaleY = 1f;
2630
2631        /**
2632         * The x location of the point around which the view is rotated and scaled.
2633         */
2634        @ViewDebug.ExportedProperty
2635        float mPivotX = 0f;
2636
2637        /**
2638         * The y location of the point around which the view is rotated and scaled.
2639         */
2640        @ViewDebug.ExportedProperty
2641        float mPivotY = 0f;
2642
2643        /**
2644         * The opacity of the View. This is a value from 0 to 1, where 0 means
2645         * completely transparent and 1 means completely opaque.
2646         */
2647        @ViewDebug.ExportedProperty
2648        float mAlpha = 1f;
2649    }
2650
2651    TransformationInfo mTransformationInfo;
2652
2653    private boolean mLastIsOpaque;
2654
2655    /**
2656     * Convenience value to check for float values that are close enough to zero to be considered
2657     * zero.
2658     */
2659    private static final float NONZERO_EPSILON = .001f;
2660
2661    /**
2662     * The distance in pixels from the left edge of this view's parent
2663     * to the left edge of this view.
2664     * {@hide}
2665     */
2666    @ViewDebug.ExportedProperty(category = "layout")
2667    protected int mLeft;
2668    /**
2669     * The distance in pixels from the left edge of this view's parent
2670     * to the right edge of this view.
2671     * {@hide}
2672     */
2673    @ViewDebug.ExportedProperty(category = "layout")
2674    protected int mRight;
2675    /**
2676     * The distance in pixels from the top edge of this view's parent
2677     * to the top edge of this view.
2678     * {@hide}
2679     */
2680    @ViewDebug.ExportedProperty(category = "layout")
2681    protected int mTop;
2682    /**
2683     * The distance in pixels from the top edge of this view's parent
2684     * to the bottom edge of this view.
2685     * {@hide}
2686     */
2687    @ViewDebug.ExportedProperty(category = "layout")
2688    protected int mBottom;
2689
2690    /**
2691     * The offset, in pixels, by which the content of this view is scrolled
2692     * horizontally.
2693     * {@hide}
2694     */
2695    @ViewDebug.ExportedProperty(category = "scrolling")
2696    protected int mScrollX;
2697    /**
2698     * The offset, in pixels, by which the content of this view is scrolled
2699     * vertically.
2700     * {@hide}
2701     */
2702    @ViewDebug.ExportedProperty(category = "scrolling")
2703    protected int mScrollY;
2704
2705    /**
2706     * The left padding in pixels, that is the distance in pixels between the
2707     * left edge of this view and the left edge of its content.
2708     * {@hide}
2709     */
2710    @ViewDebug.ExportedProperty(category = "padding")
2711    protected int mPaddingLeft;
2712    /**
2713     * The right padding in pixels, that is the distance in pixels between the
2714     * right edge of this view and the right edge of its content.
2715     * {@hide}
2716     */
2717    @ViewDebug.ExportedProperty(category = "padding")
2718    protected int mPaddingRight;
2719    /**
2720     * The top padding in pixels, that is the distance in pixels between the
2721     * top edge of this view and the top edge of its content.
2722     * {@hide}
2723     */
2724    @ViewDebug.ExportedProperty(category = "padding")
2725    protected int mPaddingTop;
2726    /**
2727     * The bottom padding in pixels, that is the distance in pixels between the
2728     * bottom edge of this view and the bottom edge of its content.
2729     * {@hide}
2730     */
2731    @ViewDebug.ExportedProperty(category = "padding")
2732    protected int mPaddingBottom;
2733
2734    /**
2735     * The layout insets in pixels, that is the distance in pixels between the
2736     * visible edges of this view its bounds.
2737     */
2738    private Insets mLayoutInsets;
2739
2740    /**
2741     * Briefly describes the view and is primarily used for accessibility support.
2742     */
2743    private CharSequence mContentDescription;
2744
2745    /**
2746     * Cache the paddingRight set by the user to append to the scrollbar's size.
2747     *
2748     * @hide
2749     */
2750    @ViewDebug.ExportedProperty(category = "padding")
2751    protected int mUserPaddingRight;
2752
2753    /**
2754     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2755     *
2756     * @hide
2757     */
2758    @ViewDebug.ExportedProperty(category = "padding")
2759    protected int mUserPaddingBottom;
2760
2761    /**
2762     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2763     *
2764     * @hide
2765     */
2766    @ViewDebug.ExportedProperty(category = "padding")
2767    protected int mUserPaddingLeft;
2768
2769    /**
2770     * Cache if the user padding is relative.
2771     *
2772     */
2773    @ViewDebug.ExportedProperty(category = "padding")
2774    boolean mUserPaddingRelative;
2775
2776    /**
2777     * Cache the paddingStart set by the user to append to the scrollbar's size.
2778     *
2779     */
2780    @ViewDebug.ExportedProperty(category = "padding")
2781    int mUserPaddingStart;
2782
2783    /**
2784     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2785     *
2786     */
2787    @ViewDebug.ExportedProperty(category = "padding")
2788    int mUserPaddingEnd;
2789
2790    /**
2791     * @hide
2792     */
2793    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2794    /**
2795     * @hide
2796     */
2797    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2798
2799    private Drawable mBackground;
2800
2801    private int mBackgroundResource;
2802    private boolean mBackgroundSizeChanged;
2803
2804    static class ListenerInfo {
2805        /**
2806         * Listener used to dispatch focus change events.
2807         * This field should be made private, so it is hidden from the SDK.
2808         * {@hide}
2809         */
2810        protected OnFocusChangeListener mOnFocusChangeListener;
2811
2812        /**
2813         * Listeners for layout change events.
2814         */
2815        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2816
2817        /**
2818         * Listeners for attach events.
2819         */
2820        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2821
2822        /**
2823         * Listener used to dispatch click events.
2824         * This field should be made private, so it is hidden from the SDK.
2825         * {@hide}
2826         */
2827        public OnClickListener mOnClickListener;
2828
2829        /**
2830         * Listener used to dispatch long click events.
2831         * This field should be made private, so it is hidden from the SDK.
2832         * {@hide}
2833         */
2834        protected OnLongClickListener mOnLongClickListener;
2835
2836        /**
2837         * Listener used to build the context menu.
2838         * This field should be made private, so it is hidden from the SDK.
2839         * {@hide}
2840         */
2841        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2842
2843        private OnKeyListener mOnKeyListener;
2844
2845        private OnTouchListener mOnTouchListener;
2846
2847        private OnHoverListener mOnHoverListener;
2848
2849        private OnGenericMotionListener mOnGenericMotionListener;
2850
2851        private OnDragListener mOnDragListener;
2852
2853        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2854    }
2855
2856    ListenerInfo mListenerInfo;
2857
2858    /**
2859     * The application environment this view lives in.
2860     * This field should be made private, so it is hidden from the SDK.
2861     * {@hide}
2862     */
2863    protected Context mContext;
2864
2865    private final Resources mResources;
2866
2867    private ScrollabilityCache mScrollCache;
2868
2869    private int[] mDrawableState = null;
2870
2871    /**
2872     * Set to true when drawing cache is enabled and cannot be created.
2873     *
2874     * @hide
2875     */
2876    public boolean mCachingFailed;
2877
2878    private Bitmap mDrawingCache;
2879    private Bitmap mUnscaledDrawingCache;
2880    private HardwareLayer mHardwareLayer;
2881    DisplayList mDisplayList;
2882
2883    /**
2884     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2885     * the user may specify which view to go to next.
2886     */
2887    private int mNextFocusLeftId = View.NO_ID;
2888
2889    /**
2890     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2891     * the user may specify which view to go to next.
2892     */
2893    private int mNextFocusRightId = View.NO_ID;
2894
2895    /**
2896     * When this view has focus and the next focus is {@link #FOCUS_UP},
2897     * the user may specify which view to go to next.
2898     */
2899    private int mNextFocusUpId = View.NO_ID;
2900
2901    /**
2902     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2903     * the user may specify which view to go to next.
2904     */
2905    private int mNextFocusDownId = View.NO_ID;
2906
2907    /**
2908     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2909     * the user may specify which view to go to next.
2910     */
2911    int mNextFocusForwardId = View.NO_ID;
2912
2913    private CheckForLongPress mPendingCheckForLongPress;
2914    private CheckForTap mPendingCheckForTap = null;
2915    private PerformClick mPerformClick;
2916    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2917
2918    private UnsetPressedState mUnsetPressedState;
2919
2920    /**
2921     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2922     * up event while a long press is invoked as soon as the long press duration is reached, so
2923     * a long press could be performed before the tap is checked, in which case the tap's action
2924     * should not be invoked.
2925     */
2926    private boolean mHasPerformedLongPress;
2927
2928    /**
2929     * The minimum height of the view. We'll try our best to have the height
2930     * of this view to at least this amount.
2931     */
2932    @ViewDebug.ExportedProperty(category = "measurement")
2933    private int mMinHeight;
2934
2935    /**
2936     * The minimum width of the view. We'll try our best to have the width
2937     * of this view to at least this amount.
2938     */
2939    @ViewDebug.ExportedProperty(category = "measurement")
2940    private int mMinWidth;
2941
2942    /**
2943     * The delegate to handle touch events that are physically in this view
2944     * but should be handled by another view.
2945     */
2946    private TouchDelegate mTouchDelegate = null;
2947
2948    /**
2949     * Solid color to use as a background when creating the drawing cache. Enables
2950     * the cache to use 16 bit bitmaps instead of 32 bit.
2951     */
2952    private int mDrawingCacheBackgroundColor = 0;
2953
2954    /**
2955     * Special tree observer used when mAttachInfo is null.
2956     */
2957    private ViewTreeObserver mFloatingTreeObserver;
2958
2959    /**
2960     * Cache the touch slop from the context that created the view.
2961     */
2962    private int mTouchSlop;
2963
2964    /**
2965     * Object that handles automatic animation of view properties.
2966     */
2967    private ViewPropertyAnimator mAnimator = null;
2968
2969    /**
2970     * Flag indicating that a drag can cross window boundaries.  When
2971     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2972     * with this flag set, all visible applications will be able to participate
2973     * in the drag operation and receive the dragged content.
2974     *
2975     * @hide
2976     */
2977    public static final int DRAG_FLAG_GLOBAL = 1;
2978
2979    /**
2980     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2981     */
2982    private float mVerticalScrollFactor;
2983
2984    /**
2985     * Position of the vertical scroll bar.
2986     */
2987    private int mVerticalScrollbarPosition;
2988
2989    /**
2990     * Position the scroll bar at the default position as determined by the system.
2991     */
2992    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2993
2994    /**
2995     * Position the scroll bar along the left edge.
2996     */
2997    public static final int SCROLLBAR_POSITION_LEFT = 1;
2998
2999    /**
3000     * Position the scroll bar along the right edge.
3001     */
3002    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3003
3004    /**
3005     * Indicates that the view does not have a layer.
3006     *
3007     * @see #getLayerType()
3008     * @see #setLayerType(int, android.graphics.Paint)
3009     * @see #LAYER_TYPE_SOFTWARE
3010     * @see #LAYER_TYPE_HARDWARE
3011     */
3012    public static final int LAYER_TYPE_NONE = 0;
3013
3014    /**
3015     * <p>Indicates that the view has a software layer. A software layer is backed
3016     * by a bitmap and causes the view to be rendered using Android's software
3017     * rendering pipeline, even if hardware acceleration is enabled.</p>
3018     *
3019     * <p>Software layers have various usages:</p>
3020     * <p>When the application is not using hardware acceleration, a software layer
3021     * is useful to apply a specific color filter and/or blending mode and/or
3022     * translucency to a view and all its children.</p>
3023     * <p>When the application is using hardware acceleration, a software layer
3024     * is useful to render drawing primitives not supported by the hardware
3025     * accelerated pipeline. It can also be used to cache a complex view tree
3026     * into a texture and reduce the complexity of drawing operations. For instance,
3027     * when animating a complex view tree with a translation, a software layer can
3028     * be used to render the view tree only once.</p>
3029     * <p>Software layers should be avoided when the affected view tree updates
3030     * often. Every update will require to re-render the software layer, which can
3031     * potentially be slow (particularly when hardware acceleration is turned on
3032     * since the layer will have to be uploaded into a hardware texture after every
3033     * update.)</p>
3034     *
3035     * @see #getLayerType()
3036     * @see #setLayerType(int, android.graphics.Paint)
3037     * @see #LAYER_TYPE_NONE
3038     * @see #LAYER_TYPE_HARDWARE
3039     */
3040    public static final int LAYER_TYPE_SOFTWARE = 1;
3041
3042    /**
3043     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3044     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3045     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3046     * rendering pipeline, but only if hardware acceleration is turned on for the
3047     * view hierarchy. When hardware acceleration is turned off, hardware layers
3048     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3049     *
3050     * <p>A hardware layer is useful to apply a specific color filter and/or
3051     * blending mode and/or translucency to a view and all its children.</p>
3052     * <p>A hardware layer can be used to cache a complex view tree into a
3053     * texture and reduce the complexity of drawing operations. For instance,
3054     * when animating a complex view tree with a translation, a hardware layer can
3055     * be used to render the view tree only once.</p>
3056     * <p>A hardware layer can also be used to increase the rendering quality when
3057     * rotation transformations are applied on a view. It can also be used to
3058     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3059     *
3060     * @see #getLayerType()
3061     * @see #setLayerType(int, android.graphics.Paint)
3062     * @see #LAYER_TYPE_NONE
3063     * @see #LAYER_TYPE_SOFTWARE
3064     */
3065    public static final int LAYER_TYPE_HARDWARE = 2;
3066
3067    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3068            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3069            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3070            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3071    })
3072    int mLayerType = LAYER_TYPE_NONE;
3073    Paint mLayerPaint;
3074    Rect mLocalDirtyRect;
3075
3076    /**
3077     * Set to true when the view is sending hover accessibility events because it
3078     * is the innermost hovered view.
3079     */
3080    private boolean mSendingHoverAccessibilityEvents;
3081
3082    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3083
3084    /**
3085     * Simple constructor to use when creating a view from code.
3086     *
3087     * @param context The Context the view is running in, through which it can
3088     *        access the current theme, resources, etc.
3089     */
3090    public View(Context context) {
3091        mContext = context;
3092        mResources = context != null ? context.getResources() : null;
3093        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3094        // Set layout and text direction defaults
3095        mPrivateFlags2 = (LAYOUT_DIRECTION_DEFAULT << LAYOUT_DIRECTION_MASK_SHIFT) |
3096                (TEXT_DIRECTION_DEFAULT << TEXT_DIRECTION_MASK_SHIFT) |
3097                (TEXT_ALIGNMENT_DEFAULT << TEXT_ALIGNMENT_MASK_SHIFT) |
3098                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3099        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3100        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3101        mUserPaddingStart = -1;
3102        mUserPaddingEnd = -1;
3103        mUserPaddingRelative = false;
3104    }
3105
3106    /**
3107     * Delegate for injecting accessiblity functionality.
3108     */
3109    AccessibilityDelegate mAccessibilityDelegate;
3110
3111    /**
3112     * Consistency verifier for debugging purposes.
3113     * @hide
3114     */
3115    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3116            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3117                    new InputEventConsistencyVerifier(this, 0) : null;
3118
3119    /**
3120     * Constructor that is called when inflating a view from XML. This is called
3121     * when a view is being constructed from an XML file, supplying attributes
3122     * that were specified in the XML file. This version uses a default style of
3123     * 0, so the only attribute values applied are those in the Context's Theme
3124     * and the given AttributeSet.
3125     *
3126     * <p>
3127     * The method onFinishInflate() will be called after all children have been
3128     * added.
3129     *
3130     * @param context The Context the view is running in, through which it can
3131     *        access the current theme, resources, etc.
3132     * @param attrs The attributes of the XML tag that is inflating the view.
3133     * @see #View(Context, AttributeSet, int)
3134     */
3135    public View(Context context, AttributeSet attrs) {
3136        this(context, attrs, 0);
3137    }
3138
3139    /**
3140     * Perform inflation from XML and apply a class-specific base style. This
3141     * constructor of View allows subclasses to use their own base style when
3142     * they are inflating. For example, a Button class's constructor would call
3143     * this version of the super class constructor and supply
3144     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3145     * the theme's button style to modify all of the base view attributes (in
3146     * particular its background) as well as the Button class's attributes.
3147     *
3148     * @param context The Context the view is running in, through which it can
3149     *        access the current theme, resources, etc.
3150     * @param attrs The attributes of the XML tag that is inflating the view.
3151     * @param defStyle The default style to apply to this view. If 0, no style
3152     *        will be applied (beyond what is included in the theme). This may
3153     *        either be an attribute resource, whose value will be retrieved
3154     *        from the current theme, or an explicit style resource.
3155     * @see #View(Context, AttributeSet)
3156     */
3157    public View(Context context, AttributeSet attrs, int defStyle) {
3158        this(context);
3159
3160        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3161                defStyle, 0);
3162
3163        Drawable background = null;
3164
3165        int leftPadding = -1;
3166        int topPadding = -1;
3167        int rightPadding = -1;
3168        int bottomPadding = -1;
3169        int startPadding = -1;
3170        int endPadding = -1;
3171
3172        int padding = -1;
3173
3174        int viewFlagValues = 0;
3175        int viewFlagMasks = 0;
3176
3177        boolean setScrollContainer = false;
3178
3179        int x = 0;
3180        int y = 0;
3181
3182        float tx = 0;
3183        float ty = 0;
3184        float rotation = 0;
3185        float rotationX = 0;
3186        float rotationY = 0;
3187        float sx = 1f;
3188        float sy = 1f;
3189        boolean transformSet = false;
3190
3191        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3192
3193        int overScrollMode = mOverScrollMode;
3194        final int N = a.getIndexCount();
3195        for (int i = 0; i < N; i++) {
3196            int attr = a.getIndex(i);
3197            switch (attr) {
3198                case com.android.internal.R.styleable.View_background:
3199                    background = a.getDrawable(attr);
3200                    break;
3201                case com.android.internal.R.styleable.View_padding:
3202                    padding = a.getDimensionPixelSize(attr, -1);
3203                    break;
3204                 case com.android.internal.R.styleable.View_paddingLeft:
3205                    leftPadding = a.getDimensionPixelSize(attr, -1);
3206                    break;
3207                case com.android.internal.R.styleable.View_paddingTop:
3208                    topPadding = a.getDimensionPixelSize(attr, -1);
3209                    break;
3210                case com.android.internal.R.styleable.View_paddingRight:
3211                    rightPadding = a.getDimensionPixelSize(attr, -1);
3212                    break;
3213                case com.android.internal.R.styleable.View_paddingBottom:
3214                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3215                    break;
3216                case com.android.internal.R.styleable.View_paddingStart:
3217                    startPadding = a.getDimensionPixelSize(attr, -1);
3218                    break;
3219                case com.android.internal.R.styleable.View_paddingEnd:
3220                    endPadding = a.getDimensionPixelSize(attr, -1);
3221                    break;
3222                case com.android.internal.R.styleable.View_scrollX:
3223                    x = a.getDimensionPixelOffset(attr, 0);
3224                    break;
3225                case com.android.internal.R.styleable.View_scrollY:
3226                    y = a.getDimensionPixelOffset(attr, 0);
3227                    break;
3228                case com.android.internal.R.styleable.View_alpha:
3229                    setAlpha(a.getFloat(attr, 1f));
3230                    break;
3231                case com.android.internal.R.styleable.View_transformPivotX:
3232                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3233                    break;
3234                case com.android.internal.R.styleable.View_transformPivotY:
3235                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3236                    break;
3237                case com.android.internal.R.styleable.View_translationX:
3238                    tx = a.getDimensionPixelOffset(attr, 0);
3239                    transformSet = true;
3240                    break;
3241                case com.android.internal.R.styleable.View_translationY:
3242                    ty = a.getDimensionPixelOffset(attr, 0);
3243                    transformSet = true;
3244                    break;
3245                case com.android.internal.R.styleable.View_rotation:
3246                    rotation = a.getFloat(attr, 0);
3247                    transformSet = true;
3248                    break;
3249                case com.android.internal.R.styleable.View_rotationX:
3250                    rotationX = a.getFloat(attr, 0);
3251                    transformSet = true;
3252                    break;
3253                case com.android.internal.R.styleable.View_rotationY:
3254                    rotationY = a.getFloat(attr, 0);
3255                    transformSet = true;
3256                    break;
3257                case com.android.internal.R.styleable.View_scaleX:
3258                    sx = a.getFloat(attr, 1f);
3259                    transformSet = true;
3260                    break;
3261                case com.android.internal.R.styleable.View_scaleY:
3262                    sy = a.getFloat(attr, 1f);
3263                    transformSet = true;
3264                    break;
3265                case com.android.internal.R.styleable.View_id:
3266                    mID = a.getResourceId(attr, NO_ID);
3267                    break;
3268                case com.android.internal.R.styleable.View_tag:
3269                    mTag = a.getText(attr);
3270                    break;
3271                case com.android.internal.R.styleable.View_fitsSystemWindows:
3272                    if (a.getBoolean(attr, false)) {
3273                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3274                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3275                    }
3276                    break;
3277                case com.android.internal.R.styleable.View_focusable:
3278                    if (a.getBoolean(attr, false)) {
3279                        viewFlagValues |= FOCUSABLE;
3280                        viewFlagMasks |= FOCUSABLE_MASK;
3281                    }
3282                    break;
3283                case com.android.internal.R.styleable.View_focusableInTouchMode:
3284                    if (a.getBoolean(attr, false)) {
3285                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3286                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3287                    }
3288                    break;
3289                case com.android.internal.R.styleable.View_clickable:
3290                    if (a.getBoolean(attr, false)) {
3291                        viewFlagValues |= CLICKABLE;
3292                        viewFlagMasks |= CLICKABLE;
3293                    }
3294                    break;
3295                case com.android.internal.R.styleable.View_longClickable:
3296                    if (a.getBoolean(attr, false)) {
3297                        viewFlagValues |= LONG_CLICKABLE;
3298                        viewFlagMasks |= LONG_CLICKABLE;
3299                    }
3300                    break;
3301                case com.android.internal.R.styleable.View_saveEnabled:
3302                    if (!a.getBoolean(attr, true)) {
3303                        viewFlagValues |= SAVE_DISABLED;
3304                        viewFlagMasks |= SAVE_DISABLED_MASK;
3305                    }
3306                    break;
3307                case com.android.internal.R.styleable.View_duplicateParentState:
3308                    if (a.getBoolean(attr, false)) {
3309                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3310                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3311                    }
3312                    break;
3313                case com.android.internal.R.styleable.View_visibility:
3314                    final int visibility = a.getInt(attr, 0);
3315                    if (visibility != 0) {
3316                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3317                        viewFlagMasks |= VISIBILITY_MASK;
3318                    }
3319                    break;
3320                case com.android.internal.R.styleable.View_layoutDirection:
3321                    // Clear any layout direction flags (included resolved bits) already set
3322                    mPrivateFlags2 &= ~(LAYOUT_DIRECTION_MASK | LAYOUT_DIRECTION_RESOLVED_MASK);
3323                    // Set the layout direction flags depending on the value of the attribute
3324                    final int layoutDirection = a.getInt(attr, -1);
3325                    final int value = (layoutDirection != -1) ?
3326                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3327                    mPrivateFlags2 |= (value << LAYOUT_DIRECTION_MASK_SHIFT);
3328                    break;
3329                case com.android.internal.R.styleable.View_drawingCacheQuality:
3330                    final int cacheQuality = a.getInt(attr, 0);
3331                    if (cacheQuality != 0) {
3332                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3333                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3334                    }
3335                    break;
3336                case com.android.internal.R.styleable.View_contentDescription:
3337                    setContentDescription(a.getString(attr));
3338                    break;
3339                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3340                    if (!a.getBoolean(attr, true)) {
3341                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3342                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3343                    }
3344                    break;
3345                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3346                    if (!a.getBoolean(attr, true)) {
3347                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3348                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3349                    }
3350                    break;
3351                case R.styleable.View_scrollbars:
3352                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3353                    if (scrollbars != SCROLLBARS_NONE) {
3354                        viewFlagValues |= scrollbars;
3355                        viewFlagMasks |= SCROLLBARS_MASK;
3356                        initializeScrollbars(a);
3357                    }
3358                    break;
3359                //noinspection deprecation
3360                case R.styleable.View_fadingEdge:
3361                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
3362                        // Ignore the attribute starting with ICS
3363                        break;
3364                    }
3365                    // With builds < ICS, fall through and apply fading edges
3366                case R.styleable.View_requiresFadingEdge:
3367                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3368                    if (fadingEdge != FADING_EDGE_NONE) {
3369                        viewFlagValues |= fadingEdge;
3370                        viewFlagMasks |= FADING_EDGE_MASK;
3371                        initializeFadingEdge(a);
3372                    }
3373                    break;
3374                case R.styleable.View_scrollbarStyle:
3375                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3376                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3377                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3378                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3379                    }
3380                    break;
3381                case R.styleable.View_isScrollContainer:
3382                    setScrollContainer = true;
3383                    if (a.getBoolean(attr, false)) {
3384                        setScrollContainer(true);
3385                    }
3386                    break;
3387                case com.android.internal.R.styleable.View_keepScreenOn:
3388                    if (a.getBoolean(attr, false)) {
3389                        viewFlagValues |= KEEP_SCREEN_ON;
3390                        viewFlagMasks |= KEEP_SCREEN_ON;
3391                    }
3392                    break;
3393                case R.styleable.View_filterTouchesWhenObscured:
3394                    if (a.getBoolean(attr, false)) {
3395                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3396                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3397                    }
3398                    break;
3399                case R.styleable.View_nextFocusLeft:
3400                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3401                    break;
3402                case R.styleable.View_nextFocusRight:
3403                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3404                    break;
3405                case R.styleable.View_nextFocusUp:
3406                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3407                    break;
3408                case R.styleable.View_nextFocusDown:
3409                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3410                    break;
3411                case R.styleable.View_nextFocusForward:
3412                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3413                    break;
3414                case R.styleable.View_minWidth:
3415                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3416                    break;
3417                case R.styleable.View_minHeight:
3418                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3419                    break;
3420                case R.styleable.View_onClick:
3421                    if (context.isRestricted()) {
3422                        throw new IllegalStateException("The android:onClick attribute cannot "
3423                                + "be used within a restricted context");
3424                    }
3425
3426                    final String handlerName = a.getString(attr);
3427                    if (handlerName != null) {
3428                        setOnClickListener(new OnClickListener() {
3429                            private Method mHandler;
3430
3431                            public void onClick(View v) {
3432                                if (mHandler == null) {
3433                                    try {
3434                                        mHandler = getContext().getClass().getMethod(handlerName,
3435                                                View.class);
3436                                    } catch (NoSuchMethodException e) {
3437                                        int id = getId();
3438                                        String idText = id == NO_ID ? "" : " with id '"
3439                                                + getContext().getResources().getResourceEntryName(
3440                                                    id) + "'";
3441                                        throw new IllegalStateException("Could not find a method " +
3442                                                handlerName + "(View) in the activity "
3443                                                + getContext().getClass() + " for onClick handler"
3444                                                + " on view " + View.this.getClass() + idText, e);
3445                                    }
3446                                }
3447
3448                                try {
3449                                    mHandler.invoke(getContext(), View.this);
3450                                } catch (IllegalAccessException e) {
3451                                    throw new IllegalStateException("Could not execute non "
3452                                            + "public method of the activity", e);
3453                                } catch (InvocationTargetException e) {
3454                                    throw new IllegalStateException("Could not execute "
3455                                            + "method of the activity", e);
3456                                }
3457                            }
3458                        });
3459                    }
3460                    break;
3461                case R.styleable.View_overScrollMode:
3462                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3463                    break;
3464                case R.styleable.View_verticalScrollbarPosition:
3465                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3466                    break;
3467                case R.styleable.View_layerType:
3468                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3469                    break;
3470                case R.styleable.View_textDirection:
3471                    // Clear any text direction flag already set
3472                    mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
3473                    // Set the text direction flags depending on the value of the attribute
3474                    final int textDirection = a.getInt(attr, -1);
3475                    if (textDirection != -1) {
3476                        mPrivateFlags2 |= TEXT_DIRECTION_FLAGS[textDirection];
3477                    }
3478                    break;
3479                case R.styleable.View_textAlignment:
3480                    // Clear any text alignment flag already set
3481                    mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
3482                    // Set the text alignment flag depending on the value of the attribute
3483                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3484                    mPrivateFlags2 |= TEXT_ALIGNMENT_FLAGS[textAlignment];
3485                    break;
3486                case R.styleable.View_importantForAccessibility:
3487                    setImportantForAccessibility(a.getInt(attr,
3488                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3489                    break;
3490            }
3491        }
3492
3493        a.recycle();
3494
3495        setOverScrollMode(overScrollMode);
3496
3497        if (background != null) {
3498            setBackground(background);
3499        }
3500
3501        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3502        // layout direction). Those cached values will be used later during padding resolution.
3503        mUserPaddingStart = startPadding;
3504        mUserPaddingEnd = endPadding;
3505
3506        updateUserPaddingRelative();
3507
3508        if (padding >= 0) {
3509            leftPadding = padding;
3510            topPadding = padding;
3511            rightPadding = padding;
3512            bottomPadding = padding;
3513        }
3514
3515        // If the user specified the padding (either with android:padding or
3516        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3517        // use the default padding or the padding from the background drawable
3518        // (stored at this point in mPadding*)
3519        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3520                topPadding >= 0 ? topPadding : mPaddingTop,
3521                rightPadding >= 0 ? rightPadding : mPaddingRight,
3522                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3523
3524        if (viewFlagMasks != 0) {
3525            setFlags(viewFlagValues, viewFlagMasks);
3526        }
3527
3528        // Needs to be called after mViewFlags is set
3529        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3530            recomputePadding();
3531        }
3532
3533        if (x != 0 || y != 0) {
3534            scrollTo(x, y);
3535        }
3536
3537        if (transformSet) {
3538            setTranslationX(tx);
3539            setTranslationY(ty);
3540            setRotation(rotation);
3541            setRotationX(rotationX);
3542            setRotationY(rotationY);
3543            setScaleX(sx);
3544            setScaleY(sy);
3545        }
3546
3547        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3548            setScrollContainer(true);
3549        }
3550
3551        computeOpaqueFlags();
3552    }
3553
3554    private void updateUserPaddingRelative() {
3555        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3556    }
3557
3558    /**
3559     * Non-public constructor for use in testing
3560     */
3561    View() {
3562        mResources = null;
3563    }
3564
3565    /**
3566     * <p>
3567     * Initializes the fading edges from a given set of styled attributes. This
3568     * method should be called by subclasses that need fading edges and when an
3569     * instance of these subclasses is created programmatically rather than
3570     * being inflated from XML. This method is automatically called when the XML
3571     * is inflated.
3572     * </p>
3573     *
3574     * @param a the styled attributes set to initialize the fading edges from
3575     */
3576    protected void initializeFadingEdge(TypedArray a) {
3577        initScrollCache();
3578
3579        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3580                R.styleable.View_fadingEdgeLength,
3581                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3582    }
3583
3584    /**
3585     * Returns the size of the vertical faded edges used to indicate that more
3586     * content in this view is visible.
3587     *
3588     * @return The size in pixels of the vertical faded edge or 0 if vertical
3589     *         faded edges are not enabled for this view.
3590     * @attr ref android.R.styleable#View_fadingEdgeLength
3591     */
3592    public int getVerticalFadingEdgeLength() {
3593        if (isVerticalFadingEdgeEnabled()) {
3594            ScrollabilityCache cache = mScrollCache;
3595            if (cache != null) {
3596                return cache.fadingEdgeLength;
3597            }
3598        }
3599        return 0;
3600    }
3601
3602    /**
3603     * Set the size of the faded edge used to indicate that more content in this
3604     * view is available.  Will not change whether the fading edge is enabled; use
3605     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3606     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3607     * for the vertical or horizontal fading edges.
3608     *
3609     * @param length The size in pixels of the faded edge used to indicate that more
3610     *        content in this view is visible.
3611     */
3612    public void setFadingEdgeLength(int length) {
3613        initScrollCache();
3614        mScrollCache.fadingEdgeLength = length;
3615    }
3616
3617    /**
3618     * Returns the size of the horizontal faded edges used to indicate that more
3619     * content in this view is visible.
3620     *
3621     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3622     *         faded edges are not enabled for this view.
3623     * @attr ref android.R.styleable#View_fadingEdgeLength
3624     */
3625    public int getHorizontalFadingEdgeLength() {
3626        if (isHorizontalFadingEdgeEnabled()) {
3627            ScrollabilityCache cache = mScrollCache;
3628            if (cache != null) {
3629                return cache.fadingEdgeLength;
3630            }
3631        }
3632        return 0;
3633    }
3634
3635    /**
3636     * Returns the width of the vertical scrollbar.
3637     *
3638     * @return The width in pixels of the vertical scrollbar or 0 if there
3639     *         is no vertical scrollbar.
3640     */
3641    public int getVerticalScrollbarWidth() {
3642        ScrollabilityCache cache = mScrollCache;
3643        if (cache != null) {
3644            ScrollBarDrawable scrollBar = cache.scrollBar;
3645            if (scrollBar != null) {
3646                int size = scrollBar.getSize(true);
3647                if (size <= 0) {
3648                    size = cache.scrollBarSize;
3649                }
3650                return size;
3651            }
3652            return 0;
3653        }
3654        return 0;
3655    }
3656
3657    /**
3658     * Returns the height of the horizontal scrollbar.
3659     *
3660     * @return The height in pixels of the horizontal scrollbar or 0 if
3661     *         there is no horizontal scrollbar.
3662     */
3663    protected int getHorizontalScrollbarHeight() {
3664        ScrollabilityCache cache = mScrollCache;
3665        if (cache != null) {
3666            ScrollBarDrawable scrollBar = cache.scrollBar;
3667            if (scrollBar != null) {
3668                int size = scrollBar.getSize(false);
3669                if (size <= 0) {
3670                    size = cache.scrollBarSize;
3671                }
3672                return size;
3673            }
3674            return 0;
3675        }
3676        return 0;
3677    }
3678
3679    /**
3680     * <p>
3681     * Initializes the scrollbars from a given set of styled attributes. This
3682     * method should be called by subclasses that need scrollbars and when an
3683     * instance of these subclasses is created programmatically rather than
3684     * being inflated from XML. This method is automatically called when the XML
3685     * is inflated.
3686     * </p>
3687     *
3688     * @param a the styled attributes set to initialize the scrollbars from
3689     */
3690    protected void initializeScrollbars(TypedArray a) {
3691        initScrollCache();
3692
3693        final ScrollabilityCache scrollabilityCache = mScrollCache;
3694
3695        if (scrollabilityCache.scrollBar == null) {
3696            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3697        }
3698
3699        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3700
3701        if (!fadeScrollbars) {
3702            scrollabilityCache.state = ScrollabilityCache.ON;
3703        }
3704        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3705
3706
3707        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3708                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3709                        .getScrollBarFadeDuration());
3710        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3711                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3712                ViewConfiguration.getScrollDefaultDelay());
3713
3714
3715        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3716                com.android.internal.R.styleable.View_scrollbarSize,
3717                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3718
3719        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3720        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3721
3722        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3723        if (thumb != null) {
3724            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3725        }
3726
3727        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3728                false);
3729        if (alwaysDraw) {
3730            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3731        }
3732
3733        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3734        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3735
3736        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3737        if (thumb != null) {
3738            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3739        }
3740
3741        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3742                false);
3743        if (alwaysDraw) {
3744            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3745        }
3746
3747        // Apply layout direction to the new Drawables if needed
3748        final int layoutDirection = getResolvedLayoutDirection();
3749        if (track != null) {
3750            track.setLayoutDirection(layoutDirection);
3751        }
3752        if (thumb != null) {
3753            thumb.setLayoutDirection(layoutDirection);
3754        }
3755
3756        // Re-apply user/background padding so that scrollbar(s) get added
3757        resolvePadding();
3758    }
3759
3760    /**
3761     * <p>
3762     * Initalizes the scrollability cache if necessary.
3763     * </p>
3764     */
3765    private void initScrollCache() {
3766        if (mScrollCache == null) {
3767            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3768        }
3769    }
3770
3771    private ScrollabilityCache getScrollCache() {
3772        initScrollCache();
3773        return mScrollCache;
3774    }
3775
3776    /**
3777     * Set the position of the vertical scroll bar. Should be one of
3778     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3779     * {@link #SCROLLBAR_POSITION_RIGHT}.
3780     *
3781     * @param position Where the vertical scroll bar should be positioned.
3782     */
3783    public void setVerticalScrollbarPosition(int position) {
3784        if (mVerticalScrollbarPosition != position) {
3785            mVerticalScrollbarPosition = position;
3786            computeOpaqueFlags();
3787            resolvePadding();
3788        }
3789    }
3790
3791    /**
3792     * @return The position where the vertical scroll bar will show, if applicable.
3793     * @see #setVerticalScrollbarPosition(int)
3794     */
3795    public int getVerticalScrollbarPosition() {
3796        return mVerticalScrollbarPosition;
3797    }
3798
3799    ListenerInfo getListenerInfo() {
3800        if (mListenerInfo != null) {
3801            return mListenerInfo;
3802        }
3803        mListenerInfo = new ListenerInfo();
3804        return mListenerInfo;
3805    }
3806
3807    /**
3808     * Register a callback to be invoked when focus of this view changed.
3809     *
3810     * @param l The callback that will run.
3811     */
3812    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3813        getListenerInfo().mOnFocusChangeListener = l;
3814    }
3815
3816    /**
3817     * Add a listener that will be called when the bounds of the view change due to
3818     * layout processing.
3819     *
3820     * @param listener The listener that will be called when layout bounds change.
3821     */
3822    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3823        ListenerInfo li = getListenerInfo();
3824        if (li.mOnLayoutChangeListeners == null) {
3825            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3826        }
3827        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3828            li.mOnLayoutChangeListeners.add(listener);
3829        }
3830    }
3831
3832    /**
3833     * Remove a listener for layout changes.
3834     *
3835     * @param listener The listener for layout bounds change.
3836     */
3837    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3838        ListenerInfo li = mListenerInfo;
3839        if (li == null || li.mOnLayoutChangeListeners == null) {
3840            return;
3841        }
3842        li.mOnLayoutChangeListeners.remove(listener);
3843    }
3844
3845    /**
3846     * Add a listener for attach state changes.
3847     *
3848     * This listener will be called whenever this view is attached or detached
3849     * from a window. Remove the listener using
3850     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3851     *
3852     * @param listener Listener to attach
3853     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3854     */
3855    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3856        ListenerInfo li = getListenerInfo();
3857        if (li.mOnAttachStateChangeListeners == null) {
3858            li.mOnAttachStateChangeListeners
3859                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3860        }
3861        li.mOnAttachStateChangeListeners.add(listener);
3862    }
3863
3864    /**
3865     * Remove a listener for attach state changes. The listener will receive no further
3866     * notification of window attach/detach events.
3867     *
3868     * @param listener Listener to remove
3869     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3870     */
3871    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3872        ListenerInfo li = mListenerInfo;
3873        if (li == null || li.mOnAttachStateChangeListeners == null) {
3874            return;
3875        }
3876        li.mOnAttachStateChangeListeners.remove(listener);
3877    }
3878
3879    /**
3880     * Returns the focus-change callback registered for this view.
3881     *
3882     * @return The callback, or null if one is not registered.
3883     */
3884    public OnFocusChangeListener getOnFocusChangeListener() {
3885        ListenerInfo li = mListenerInfo;
3886        return li != null ? li.mOnFocusChangeListener : null;
3887    }
3888
3889    /**
3890     * Register a callback to be invoked when this view is clicked. If this view is not
3891     * clickable, it becomes clickable.
3892     *
3893     * @param l The callback that will run
3894     *
3895     * @see #setClickable(boolean)
3896     */
3897    public void setOnClickListener(OnClickListener l) {
3898        if (!isClickable()) {
3899            setClickable(true);
3900        }
3901        getListenerInfo().mOnClickListener = l;
3902    }
3903
3904    /**
3905     * Return whether this view has an attached OnClickListener.  Returns
3906     * true if there is a listener, false if there is none.
3907     */
3908    public boolean hasOnClickListeners() {
3909        ListenerInfo li = mListenerInfo;
3910        return (li != null && li.mOnClickListener != null);
3911    }
3912
3913    /**
3914     * Register a callback to be invoked when this view is clicked and held. If this view is not
3915     * long clickable, it becomes long clickable.
3916     *
3917     * @param l The callback that will run
3918     *
3919     * @see #setLongClickable(boolean)
3920     */
3921    public void setOnLongClickListener(OnLongClickListener l) {
3922        if (!isLongClickable()) {
3923            setLongClickable(true);
3924        }
3925        getListenerInfo().mOnLongClickListener = l;
3926    }
3927
3928    /**
3929     * Register a callback to be invoked when the context menu for this view is
3930     * being built. If this view is not long clickable, it becomes long clickable.
3931     *
3932     * @param l The callback that will run
3933     *
3934     */
3935    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3936        if (!isLongClickable()) {
3937            setLongClickable(true);
3938        }
3939        getListenerInfo().mOnCreateContextMenuListener = l;
3940    }
3941
3942    /**
3943     * Call this view's OnClickListener, if it is defined.  Performs all normal
3944     * actions associated with clicking: reporting accessibility event, playing
3945     * a sound, etc.
3946     *
3947     * @return True there was an assigned OnClickListener that was called, false
3948     *         otherwise is returned.
3949     */
3950    public boolean performClick() {
3951        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3952
3953        ListenerInfo li = mListenerInfo;
3954        if (li != null && li.mOnClickListener != null) {
3955            playSoundEffect(SoundEffectConstants.CLICK);
3956            li.mOnClickListener.onClick(this);
3957            return true;
3958        }
3959
3960        return false;
3961    }
3962
3963    /**
3964     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3965     * this only calls the listener, and does not do any associated clicking
3966     * actions like reporting an accessibility event.
3967     *
3968     * @return True there was an assigned OnClickListener that was called, false
3969     *         otherwise is returned.
3970     */
3971    public boolean callOnClick() {
3972        ListenerInfo li = mListenerInfo;
3973        if (li != null && li.mOnClickListener != null) {
3974            li.mOnClickListener.onClick(this);
3975            return true;
3976        }
3977        return false;
3978    }
3979
3980    /**
3981     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3982     * OnLongClickListener did not consume the event.
3983     *
3984     * @return True if one of the above receivers consumed the event, false otherwise.
3985     */
3986    public boolean performLongClick() {
3987        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3988
3989        boolean handled = false;
3990        ListenerInfo li = mListenerInfo;
3991        if (li != null && li.mOnLongClickListener != null) {
3992            handled = li.mOnLongClickListener.onLongClick(View.this);
3993        }
3994        if (!handled) {
3995            handled = showContextMenu();
3996        }
3997        if (handled) {
3998            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3999        }
4000        return handled;
4001    }
4002
4003    /**
4004     * Performs button-related actions during a touch down event.
4005     *
4006     * @param event The event.
4007     * @return True if the down was consumed.
4008     *
4009     * @hide
4010     */
4011    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4012        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4013            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4014                return true;
4015            }
4016        }
4017        return false;
4018    }
4019
4020    /**
4021     * Bring up the context menu for this view.
4022     *
4023     * @return Whether a context menu was displayed.
4024     */
4025    public boolean showContextMenu() {
4026        return getParent().showContextMenuForChild(this);
4027    }
4028
4029    /**
4030     * Bring up the context menu for this view, referring to the item under the specified point.
4031     *
4032     * @param x The referenced x coordinate.
4033     * @param y The referenced y coordinate.
4034     * @param metaState The keyboard modifiers that were pressed.
4035     * @return Whether a context menu was displayed.
4036     *
4037     * @hide
4038     */
4039    public boolean showContextMenu(float x, float y, int metaState) {
4040        return showContextMenu();
4041    }
4042
4043    /**
4044     * Start an action mode.
4045     *
4046     * @param callback Callback that will control the lifecycle of the action mode
4047     * @return The new action mode if it is started, null otherwise
4048     *
4049     * @see ActionMode
4050     */
4051    public ActionMode startActionMode(ActionMode.Callback callback) {
4052        ViewParent parent = getParent();
4053        if (parent == null) return null;
4054        return parent.startActionModeForChild(this, callback);
4055    }
4056
4057    /**
4058     * Register a callback to be invoked when a hardware key is pressed in this view.
4059     * Key presses in software input methods will generally not trigger the methods of
4060     * this listener.
4061     * @param l the key listener to attach to this view
4062     */
4063    public void setOnKeyListener(OnKeyListener l) {
4064        getListenerInfo().mOnKeyListener = l;
4065    }
4066
4067    /**
4068     * Register a callback to be invoked when a touch event is sent to this view.
4069     * @param l the touch listener to attach to this view
4070     */
4071    public void setOnTouchListener(OnTouchListener l) {
4072        getListenerInfo().mOnTouchListener = l;
4073    }
4074
4075    /**
4076     * Register a callback to be invoked when a generic motion event is sent to this view.
4077     * @param l the generic motion listener to attach to this view
4078     */
4079    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4080        getListenerInfo().mOnGenericMotionListener = l;
4081    }
4082
4083    /**
4084     * Register a callback to be invoked when a hover event is sent to this view.
4085     * @param l the hover listener to attach to this view
4086     */
4087    public void setOnHoverListener(OnHoverListener l) {
4088        getListenerInfo().mOnHoverListener = l;
4089    }
4090
4091    /**
4092     * Register a drag event listener callback object for this View. The parameter is
4093     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4094     * View, the system calls the
4095     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4096     * @param l An implementation of {@link android.view.View.OnDragListener}.
4097     */
4098    public void setOnDragListener(OnDragListener l) {
4099        getListenerInfo().mOnDragListener = l;
4100    }
4101
4102    /**
4103     * Give this view focus. This will cause
4104     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4105     *
4106     * Note: this does not check whether this {@link View} should get focus, it just
4107     * gives it focus no matter what.  It should only be called internally by framework
4108     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4109     *
4110     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4111     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4112     *        focus moved when requestFocus() is called. It may not always
4113     *        apply, in which case use the default View.FOCUS_DOWN.
4114     * @param previouslyFocusedRect The rectangle of the view that had focus
4115     *        prior in this View's coordinate system.
4116     */
4117    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4118        if (DBG) {
4119            System.out.println(this + " requestFocus()");
4120        }
4121
4122        if ((mPrivateFlags & FOCUSED) == 0) {
4123            mPrivateFlags |= FOCUSED;
4124
4125            if (mParent != null) {
4126                mParent.requestChildFocus(this, this);
4127            }
4128
4129            onFocusChanged(true, direction, previouslyFocusedRect);
4130            refreshDrawableState();
4131
4132            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4133                notifyAccessibilityStateChanged();
4134            }
4135        }
4136    }
4137
4138    /**
4139     * Request that a rectangle of this view be visible on the screen,
4140     * scrolling if necessary just enough.
4141     *
4142     * <p>A View should call this if it maintains some notion of which part
4143     * of its content is interesting.  For example, a text editing view
4144     * should call this when its cursor moves.
4145     *
4146     * @param rectangle The rectangle.
4147     * @return Whether any parent scrolled.
4148     */
4149    public boolean requestRectangleOnScreen(Rect rectangle) {
4150        return requestRectangleOnScreen(rectangle, false);
4151    }
4152
4153    /**
4154     * Request that a rectangle of this view be visible on the screen,
4155     * scrolling if necessary just enough.
4156     *
4157     * <p>A View should call this if it maintains some notion of which part
4158     * of its content is interesting.  For example, a text editing view
4159     * should call this when its cursor moves.
4160     *
4161     * <p>When <code>immediate</code> is set to true, scrolling will not be
4162     * animated.
4163     *
4164     * @param rectangle The rectangle.
4165     * @param immediate True to forbid animated scrolling, false otherwise
4166     * @return Whether any parent scrolled.
4167     */
4168    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4169        View child = this;
4170        ViewParent parent = mParent;
4171        boolean scrolled = false;
4172        while (parent != null) {
4173            scrolled |= parent.requestChildRectangleOnScreen(child,
4174                    rectangle, immediate);
4175
4176            // offset rect so next call has the rectangle in the
4177            // coordinate system of its direct child.
4178            rectangle.offset(child.getLeft(), child.getTop());
4179            rectangle.offset(-child.getScrollX(), -child.getScrollY());
4180
4181            if (!(parent instanceof View)) {
4182                break;
4183            }
4184
4185            child = (View) parent;
4186            parent = child.getParent();
4187        }
4188        return scrolled;
4189    }
4190
4191    /**
4192     * Called when this view wants to give up focus. If focus is cleared
4193     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4194     * <p>
4195     * <strong>Note:</strong> When a View clears focus the framework is trying
4196     * to give focus to the first focusable View from the top. Hence, if this
4197     * View is the first from the top that can take focus, then all callbacks
4198     * related to clearing focus will be invoked after wich the framework will
4199     * give focus to this view.
4200     * </p>
4201     */
4202    public void clearFocus() {
4203        if (DBG) {
4204            System.out.println(this + " clearFocus()");
4205        }
4206
4207        if ((mPrivateFlags & FOCUSED) != 0) {
4208            mPrivateFlags &= ~FOCUSED;
4209
4210            if (mParent != null) {
4211                mParent.clearChildFocus(this);
4212            }
4213
4214            onFocusChanged(false, 0, null);
4215
4216            refreshDrawableState();
4217
4218            ensureInputFocusOnFirstFocusable();
4219
4220            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4221                notifyAccessibilityStateChanged();
4222            }
4223        }
4224    }
4225
4226    void ensureInputFocusOnFirstFocusable() {
4227        View root = getRootView();
4228        if (root != null) {
4229            root.requestFocus();
4230        }
4231    }
4232
4233    /**
4234     * Called internally by the view system when a new view is getting focus.
4235     * This is what clears the old focus.
4236     */
4237    void unFocus() {
4238        if (DBG) {
4239            System.out.println(this + " unFocus()");
4240        }
4241
4242        if ((mPrivateFlags & FOCUSED) != 0) {
4243            mPrivateFlags &= ~FOCUSED;
4244
4245            onFocusChanged(false, 0, null);
4246            refreshDrawableState();
4247
4248            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4249                notifyAccessibilityStateChanged();
4250            }
4251        }
4252    }
4253
4254    /**
4255     * Returns true if this view has focus iteself, or is the ancestor of the
4256     * view that has focus.
4257     *
4258     * @return True if this view has or contains focus, false otherwise.
4259     */
4260    @ViewDebug.ExportedProperty(category = "focus")
4261    public boolean hasFocus() {
4262        return (mPrivateFlags & FOCUSED) != 0;
4263    }
4264
4265    /**
4266     * Returns true if this view is focusable or if it contains a reachable View
4267     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4268     * is a View whose parents do not block descendants focus.
4269     *
4270     * Only {@link #VISIBLE} views are considered focusable.
4271     *
4272     * @return True if the view is focusable or if the view contains a focusable
4273     *         View, false otherwise.
4274     *
4275     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4276     */
4277    public boolean hasFocusable() {
4278        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4279    }
4280
4281    /**
4282     * Called by the view system when the focus state of this view changes.
4283     * When the focus change event is caused by directional navigation, direction
4284     * and previouslyFocusedRect provide insight into where the focus is coming from.
4285     * When overriding, be sure to call up through to the super class so that
4286     * the standard focus handling will occur.
4287     *
4288     * @param gainFocus True if the View has focus; false otherwise.
4289     * @param direction The direction focus has moved when requestFocus()
4290     *                  is called to give this view focus. Values are
4291     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4292     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4293     *                  It may not always apply, in which case use the default.
4294     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4295     *        system, of the previously focused view.  If applicable, this will be
4296     *        passed in as finer grained information about where the focus is coming
4297     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4298     */
4299    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4300        if (gainFocus) {
4301            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4302                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4303            }
4304        }
4305
4306        InputMethodManager imm = InputMethodManager.peekInstance();
4307        if (!gainFocus) {
4308            if (isPressed()) {
4309                setPressed(false);
4310            }
4311            if (imm != null && mAttachInfo != null
4312                    && mAttachInfo.mHasWindowFocus) {
4313                imm.focusOut(this);
4314            }
4315            onFocusLost();
4316        } else if (imm != null && mAttachInfo != null
4317                && mAttachInfo.mHasWindowFocus) {
4318            imm.focusIn(this);
4319        }
4320
4321        invalidate(true);
4322        ListenerInfo li = mListenerInfo;
4323        if (li != null && li.mOnFocusChangeListener != null) {
4324            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4325        }
4326
4327        if (mAttachInfo != null) {
4328            mAttachInfo.mKeyDispatchState.reset(this);
4329        }
4330    }
4331
4332    /**
4333     * Sends an accessibility event of the given type. If accessiiblity is
4334     * not enabled this method has no effect. The default implementation calls
4335     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4336     * to populate information about the event source (this View), then calls
4337     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4338     * populate the text content of the event source including its descendants,
4339     * and last calls
4340     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4341     * on its parent to resuest sending of the event to interested parties.
4342     * <p>
4343     * If an {@link AccessibilityDelegate} has been specified via calling
4344     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4345     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4346     * responsible for handling this call.
4347     * </p>
4348     *
4349     * @param eventType The type of the event to send, as defined by several types from
4350     * {@link android.view.accessibility.AccessibilityEvent}, such as
4351     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4352     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4353     *
4354     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4355     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4356     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4357     * @see AccessibilityDelegate
4358     */
4359    public void sendAccessibilityEvent(int eventType) {
4360        if (mAccessibilityDelegate != null) {
4361            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4362        } else {
4363            sendAccessibilityEventInternal(eventType);
4364        }
4365    }
4366
4367    /**
4368     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4369     * {@link AccessibilityEvent} to make an announcement which is related to some
4370     * sort of a context change for which none of the events representing UI transitions
4371     * is a good fit. For example, announcing a new page in a book. If accessibility
4372     * is not enabled this method does nothing.
4373     *
4374     * @param text The announcement text.
4375     */
4376    public void announceForAccessibility(CharSequence text) {
4377        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4378            AccessibilityEvent event = AccessibilityEvent.obtain(
4379                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4380            onInitializeAccessibilityEvent(event);
4381            event.getText().add(text);
4382            event.setContentDescription(null);
4383            mParent.requestSendAccessibilityEvent(this, event);
4384        }
4385    }
4386
4387    /**
4388     * @see #sendAccessibilityEvent(int)
4389     *
4390     * Note: Called from the default {@link AccessibilityDelegate}.
4391     */
4392    void sendAccessibilityEventInternal(int eventType) {
4393        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4394            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4395        }
4396    }
4397
4398    /**
4399     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4400     * takes as an argument an empty {@link AccessibilityEvent} and does not
4401     * perform a check whether accessibility is enabled.
4402     * <p>
4403     * If an {@link AccessibilityDelegate} has been specified via calling
4404     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4405     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4406     * is responsible for handling this call.
4407     * </p>
4408     *
4409     * @param event The event to send.
4410     *
4411     * @see #sendAccessibilityEvent(int)
4412     */
4413    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4414        if (mAccessibilityDelegate != null) {
4415            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4416        } else {
4417            sendAccessibilityEventUncheckedInternal(event);
4418        }
4419    }
4420
4421    /**
4422     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4423     *
4424     * Note: Called from the default {@link AccessibilityDelegate}.
4425     */
4426    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4427        if (!isShown()) {
4428            return;
4429        }
4430        onInitializeAccessibilityEvent(event);
4431        // Only a subset of accessibility events populates text content.
4432        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4433            dispatchPopulateAccessibilityEvent(event);
4434        }
4435        // In the beginning we called #isShown(), so we know that getParent() is not null.
4436        getParent().requestSendAccessibilityEvent(this, event);
4437    }
4438
4439    /**
4440     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4441     * to its children for adding their text content to the event. Note that the
4442     * event text is populated in a separate dispatch path since we add to the
4443     * event not only the text of the source but also the text of all its descendants.
4444     * A typical implementation will call
4445     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4446     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4447     * on each child. Override this method if custom population of the event text
4448     * content is required.
4449     * <p>
4450     * If an {@link AccessibilityDelegate} has been specified via calling
4451     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4452     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4453     * is responsible for handling this call.
4454     * </p>
4455     * <p>
4456     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4457     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4458     * </p>
4459     *
4460     * @param event The event.
4461     *
4462     * @return True if the event population was completed.
4463     */
4464    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4465        if (mAccessibilityDelegate != null) {
4466            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4467        } else {
4468            return dispatchPopulateAccessibilityEventInternal(event);
4469        }
4470    }
4471
4472    /**
4473     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4474     *
4475     * Note: Called from the default {@link AccessibilityDelegate}.
4476     */
4477    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4478        onPopulateAccessibilityEvent(event);
4479        return false;
4480    }
4481
4482    /**
4483     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4484     * giving a chance to this View to populate the accessibility event with its
4485     * text content. While this method is free to modify event
4486     * attributes other than text content, doing so should normally be performed in
4487     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4488     * <p>
4489     * Example: Adding formatted date string to an accessibility event in addition
4490     *          to the text added by the super implementation:
4491     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4492     *     super.onPopulateAccessibilityEvent(event);
4493     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4494     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4495     *         mCurrentDate.getTimeInMillis(), flags);
4496     *     event.getText().add(selectedDateUtterance);
4497     * }</pre>
4498     * <p>
4499     * If an {@link AccessibilityDelegate} has been specified via calling
4500     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4501     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4502     * is responsible for handling this call.
4503     * </p>
4504     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4505     * information to the event, in case the default implementation has basic information to add.
4506     * </p>
4507     *
4508     * @param event The accessibility event which to populate.
4509     *
4510     * @see #sendAccessibilityEvent(int)
4511     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4512     */
4513    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4514        if (mAccessibilityDelegate != null) {
4515            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4516        } else {
4517            onPopulateAccessibilityEventInternal(event);
4518        }
4519    }
4520
4521    /**
4522     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4523     *
4524     * Note: Called from the default {@link AccessibilityDelegate}.
4525     */
4526    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4527
4528    }
4529
4530    /**
4531     * Initializes an {@link AccessibilityEvent} with information about
4532     * this View which is the event source. In other words, the source of
4533     * an accessibility event is the view whose state change triggered firing
4534     * the event.
4535     * <p>
4536     * Example: Setting the password property of an event in addition
4537     *          to properties set by the super implementation:
4538     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4539     *     super.onInitializeAccessibilityEvent(event);
4540     *     event.setPassword(true);
4541     * }</pre>
4542     * <p>
4543     * If an {@link AccessibilityDelegate} has been specified via calling
4544     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4545     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4546     * is responsible for handling this call.
4547     * </p>
4548     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4549     * information to the event, in case the default implementation has basic information to add.
4550     * </p>
4551     * @param event The event to initialize.
4552     *
4553     * @see #sendAccessibilityEvent(int)
4554     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4555     */
4556    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4557        if (mAccessibilityDelegate != null) {
4558            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4559        } else {
4560            onInitializeAccessibilityEventInternal(event);
4561        }
4562    }
4563
4564    /**
4565     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4566     *
4567     * Note: Called from the default {@link AccessibilityDelegate}.
4568     */
4569    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4570        event.setSource(this);
4571        event.setClassName(View.class.getName());
4572        event.setPackageName(getContext().getPackageName());
4573        event.setEnabled(isEnabled());
4574        event.setContentDescription(mContentDescription);
4575
4576        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4577            ArrayList<View> focusablesTempList = mAttachInfo.mTempArrayList;
4578            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4579                    FOCUSABLES_ALL);
4580            event.setItemCount(focusablesTempList.size());
4581            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4582            focusablesTempList.clear();
4583        }
4584    }
4585
4586    /**
4587     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4588     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4589     * This method is responsible for obtaining an accessibility node info from a
4590     * pool of reusable instances and calling
4591     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4592     * initialize the former.
4593     * <p>
4594     * Note: The client is responsible for recycling the obtained instance by calling
4595     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4596     * </p>
4597     *
4598     * @return A populated {@link AccessibilityNodeInfo}.
4599     *
4600     * @see AccessibilityNodeInfo
4601     */
4602    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4603        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4604        if (provider != null) {
4605            return provider.createAccessibilityNodeInfo(View.NO_ID);
4606        } else {
4607            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4608            onInitializeAccessibilityNodeInfo(info);
4609            return info;
4610        }
4611    }
4612
4613    /**
4614     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4615     * The base implementation sets:
4616     * <ul>
4617     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4618     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4619     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4620     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4621     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4622     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4623     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4624     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4625     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4626     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4627     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4628     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4629     * </ul>
4630     * <p>
4631     * Subclasses should override this method, call the super implementation,
4632     * and set additional attributes.
4633     * </p>
4634     * <p>
4635     * If an {@link AccessibilityDelegate} has been specified via calling
4636     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4637     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4638     * is responsible for handling this call.
4639     * </p>
4640     *
4641     * @param info The instance to initialize.
4642     */
4643    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4644        if (mAccessibilityDelegate != null) {
4645            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4646        } else {
4647            onInitializeAccessibilityNodeInfoInternal(info);
4648        }
4649    }
4650
4651    /**
4652     * Gets the location of this view in screen coordintates.
4653     *
4654     * @param outRect The output location
4655     */
4656    private void getBoundsOnScreen(Rect outRect) {
4657        if (mAttachInfo == null) {
4658            return;
4659        }
4660
4661        RectF position = mAttachInfo.mTmpTransformRect;
4662        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4663
4664        if (!hasIdentityMatrix()) {
4665            getMatrix().mapRect(position);
4666        }
4667
4668        position.offset(mLeft, mTop);
4669
4670        ViewParent parent = mParent;
4671        while (parent instanceof View) {
4672            View parentView = (View) parent;
4673
4674            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4675
4676            if (!parentView.hasIdentityMatrix()) {
4677                parentView.getMatrix().mapRect(position);
4678            }
4679
4680            position.offset(parentView.mLeft, parentView.mTop);
4681
4682            parent = parentView.mParent;
4683        }
4684
4685        if (parent instanceof ViewRootImpl) {
4686            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
4687            position.offset(0, -viewRootImpl.mCurScrollY);
4688        }
4689
4690        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
4691
4692        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
4693                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
4694    }
4695
4696    /**
4697     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4698     *
4699     * Note: Called from the default {@link AccessibilityDelegate}.
4700     */
4701    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4702        Rect bounds = mAttachInfo.mTmpInvalRect;
4703
4704        getDrawingRect(bounds);
4705        info.setBoundsInParent(bounds);
4706
4707        getBoundsOnScreen(bounds);
4708        info.setBoundsInScreen(bounds);
4709
4710        ViewParent parent = getParentForAccessibility();
4711        if (parent instanceof View) {
4712            info.setParent((View) parent);
4713        }
4714
4715        info.setVisibleToUser(isVisibleToUser());
4716
4717        info.setPackageName(mContext.getPackageName());
4718        info.setClassName(View.class.getName());
4719        info.setContentDescription(getContentDescription());
4720
4721        info.setEnabled(isEnabled());
4722        info.setClickable(isClickable());
4723        info.setFocusable(isFocusable());
4724        info.setFocused(isFocused());
4725        info.setAccessibilityFocused(isAccessibilityFocused());
4726        info.setSelected(isSelected());
4727        info.setLongClickable(isLongClickable());
4728
4729        // TODO: These make sense only if we are in an AdapterView but all
4730        // views can be selected. Maybe from accessiiblity perspective
4731        // we should report as selectable view in an AdapterView.
4732        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4733        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4734
4735        if (isFocusable()) {
4736            if (isFocused()) {
4737                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4738            } else {
4739                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4740            }
4741        }
4742
4743        if (!isAccessibilityFocused()) {
4744            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
4745        } else {
4746            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
4747        }
4748
4749        if (isClickable() && isEnabled()) {
4750            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
4751        }
4752
4753        if (isLongClickable() && isEnabled()) {
4754            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
4755        }
4756
4757        if (mContentDescription != null && mContentDescription.length() > 0) {
4758            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
4759            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
4760            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
4761                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
4762                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
4763        }
4764    }
4765
4766    /**
4767     * Computes whether this view is visible to the user. Such a view is
4768     * attached, visible, all its predecessors are visible, it is not clipped
4769     * entirely by its predecessors, and has an alpha greater than zero.
4770     *
4771     * @return Whether the view is visible on the screen.
4772     *
4773     * @hide
4774     */
4775    protected boolean isVisibleToUser() {
4776        return isVisibleToUser(null);
4777    }
4778
4779    /**
4780     * Computes whether the given portion of this view is visible to the user.
4781     * Such a view is attached, visible, all its predecessors are visible,
4782     * has an alpha greater than zero, and the specified portion is not
4783     * clipped entirely by its predecessors.
4784     *
4785     * @param boundInView the portion of the view to test; coordinates should be relative; may be
4786     *                    <code>null</code>, and the entire view will be tested in this case.
4787     *                    When <code>true</code> is returned by the function, the actual visible
4788     *                    region will be stored in this parameter; that is, if boundInView is fully
4789     *                    contained within the view, no modification will be made, otherwise regions
4790     *                    outside of the visible area of the view will be clipped.
4791     *
4792     * @return Whether the specified portion of the view is visible on the screen.
4793     *
4794     * @hide
4795     */
4796    protected boolean isVisibleToUser(Rect boundInView) {
4797        if (mAttachInfo != null) {
4798            Rect visibleRect = mAttachInfo.mTmpInvalRect;
4799            Point offset = mAttachInfo.mPoint;
4800            // The first two checks are made also made by isShown() which
4801            // however traverses the tree up to the parent to catch that.
4802            // Therefore, we do some fail fast check to minimize the up
4803            // tree traversal.
4804            boolean isVisible = mAttachInfo.mWindowVisibility == View.VISIBLE
4805                && getAlpha() > 0
4806                && isShown()
4807                && getGlobalVisibleRect(visibleRect, offset);
4808            if (isVisible && boundInView != null) {
4809                visibleRect.offset(-offset.x, -offset.y);
4810                // isVisible is always true here, use a simple assignment
4811                isVisible = boundInView.intersect(visibleRect);
4812            }
4813            return isVisible;
4814        }
4815
4816        return false;
4817    }
4818
4819    /**
4820     * Sets a delegate for implementing accessibility support via compositon as
4821     * opposed to inheritance. The delegate's primary use is for implementing
4822     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4823     *
4824     * @param delegate The delegate instance.
4825     *
4826     * @see AccessibilityDelegate
4827     */
4828    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4829        mAccessibilityDelegate = delegate;
4830    }
4831
4832    /**
4833     * Gets the provider for managing a virtual view hierarchy rooted at this View
4834     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4835     * that explore the window content.
4836     * <p>
4837     * If this method returns an instance, this instance is responsible for managing
4838     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4839     * View including the one representing the View itself. Similarly the returned
4840     * instance is responsible for performing accessibility actions on any virtual
4841     * view or the root view itself.
4842     * </p>
4843     * <p>
4844     * If an {@link AccessibilityDelegate} has been specified via calling
4845     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4846     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4847     * is responsible for handling this call.
4848     * </p>
4849     *
4850     * @return The provider.
4851     *
4852     * @see AccessibilityNodeProvider
4853     */
4854    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4855        if (mAccessibilityDelegate != null) {
4856            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4857        } else {
4858            return null;
4859        }
4860    }
4861
4862    /**
4863     * Gets the unique identifier of this view on the screen for accessibility purposes.
4864     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4865     *
4866     * @return The view accessibility id.
4867     *
4868     * @hide
4869     */
4870    public int getAccessibilityViewId() {
4871        if (mAccessibilityViewId == NO_ID) {
4872            mAccessibilityViewId = sNextAccessibilityViewId++;
4873        }
4874        return mAccessibilityViewId;
4875    }
4876
4877    /**
4878     * Gets the unique identifier of the window in which this View reseides.
4879     *
4880     * @return The window accessibility id.
4881     *
4882     * @hide
4883     */
4884    public int getAccessibilityWindowId() {
4885        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4886    }
4887
4888    /**
4889     * Gets the {@link View} description. It briefly describes the view and is
4890     * primarily used for accessibility support. Set this property to enable
4891     * better accessibility support for your application. This is especially
4892     * true for views that do not have textual representation (For example,
4893     * ImageButton).
4894     *
4895     * @return The content description.
4896     *
4897     * @attr ref android.R.styleable#View_contentDescription
4898     */
4899    @ViewDebug.ExportedProperty(category = "accessibility")
4900    public CharSequence getContentDescription() {
4901        return mContentDescription;
4902    }
4903
4904    /**
4905     * Sets the {@link View} description. It briefly describes the view and is
4906     * primarily used for accessibility support. Set this property to enable
4907     * better accessibility support for your application. This is especially
4908     * true for views that do not have textual representation (For example,
4909     * ImageButton).
4910     *
4911     * @param contentDescription The content description.
4912     *
4913     * @attr ref android.R.styleable#View_contentDescription
4914     */
4915    @RemotableViewMethod
4916    public void setContentDescription(CharSequence contentDescription) {
4917        mContentDescription = contentDescription;
4918        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
4919        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
4920             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
4921        }
4922    }
4923
4924    /**
4925     * Invoked whenever this view loses focus, either by losing window focus or by losing
4926     * focus within its window. This method can be used to clear any state tied to the
4927     * focus. For instance, if a button is held pressed with the trackball and the window
4928     * loses focus, this method can be used to cancel the press.
4929     *
4930     * Subclasses of View overriding this method should always call super.onFocusLost().
4931     *
4932     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4933     * @see #onWindowFocusChanged(boolean)
4934     *
4935     * @hide pending API council approval
4936     */
4937    protected void onFocusLost() {
4938        resetPressedState();
4939    }
4940
4941    private void resetPressedState() {
4942        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4943            return;
4944        }
4945
4946        if (isPressed()) {
4947            setPressed(false);
4948
4949            if (!mHasPerformedLongPress) {
4950                removeLongPressCallback();
4951            }
4952        }
4953    }
4954
4955    /**
4956     * Returns true if this view has focus
4957     *
4958     * @return True if this view has focus, false otherwise.
4959     */
4960    @ViewDebug.ExportedProperty(category = "focus")
4961    public boolean isFocused() {
4962        return (mPrivateFlags & FOCUSED) != 0;
4963    }
4964
4965    /**
4966     * Find the view in the hierarchy rooted at this view that currently has
4967     * focus.
4968     *
4969     * @return The view that currently has focus, or null if no focused view can
4970     *         be found.
4971     */
4972    public View findFocus() {
4973        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4974    }
4975
4976    /**
4977     * Indicates whether this view is one of the set of scrollable containers in
4978     * its window.
4979     *
4980     * @return whether this view is one of the set of scrollable containers in
4981     * its window
4982     *
4983     * @attr ref android.R.styleable#View_isScrollContainer
4984     */
4985    public boolean isScrollContainer() {
4986        return (mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0;
4987    }
4988
4989    /**
4990     * Change whether this view is one of the set of scrollable containers in
4991     * its window.  This will be used to determine whether the window can
4992     * resize or must pan when a soft input area is open -- scrollable
4993     * containers allow the window to use resize mode since the container
4994     * will appropriately shrink.
4995     *
4996     * @attr ref android.R.styleable#View_isScrollContainer
4997     */
4998    public void setScrollContainer(boolean isScrollContainer) {
4999        if (isScrollContainer) {
5000            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
5001                mAttachInfo.mScrollContainers.add(this);
5002                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
5003            }
5004            mPrivateFlags |= SCROLL_CONTAINER;
5005        } else {
5006            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
5007                mAttachInfo.mScrollContainers.remove(this);
5008            }
5009            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
5010        }
5011    }
5012
5013    /**
5014     * Returns the quality of the drawing cache.
5015     *
5016     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5017     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5018     *
5019     * @see #setDrawingCacheQuality(int)
5020     * @see #setDrawingCacheEnabled(boolean)
5021     * @see #isDrawingCacheEnabled()
5022     *
5023     * @attr ref android.R.styleable#View_drawingCacheQuality
5024     */
5025    public int getDrawingCacheQuality() {
5026        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5027    }
5028
5029    /**
5030     * Set the drawing cache quality of this view. This value is used only when the
5031     * drawing cache is enabled
5032     *
5033     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5034     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5035     *
5036     * @see #getDrawingCacheQuality()
5037     * @see #setDrawingCacheEnabled(boolean)
5038     * @see #isDrawingCacheEnabled()
5039     *
5040     * @attr ref android.R.styleable#View_drawingCacheQuality
5041     */
5042    public void setDrawingCacheQuality(int quality) {
5043        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5044    }
5045
5046    /**
5047     * Returns whether the screen should remain on, corresponding to the current
5048     * value of {@link #KEEP_SCREEN_ON}.
5049     *
5050     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5051     *
5052     * @see #setKeepScreenOn(boolean)
5053     *
5054     * @attr ref android.R.styleable#View_keepScreenOn
5055     */
5056    public boolean getKeepScreenOn() {
5057        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5058    }
5059
5060    /**
5061     * Controls whether the screen should remain on, modifying the
5062     * value of {@link #KEEP_SCREEN_ON}.
5063     *
5064     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5065     *
5066     * @see #getKeepScreenOn()
5067     *
5068     * @attr ref android.R.styleable#View_keepScreenOn
5069     */
5070    public void setKeepScreenOn(boolean keepScreenOn) {
5071        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5072    }
5073
5074    /**
5075     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5076     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5077     *
5078     * @attr ref android.R.styleable#View_nextFocusLeft
5079     */
5080    public int getNextFocusLeftId() {
5081        return mNextFocusLeftId;
5082    }
5083
5084    /**
5085     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5086     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5087     * decide automatically.
5088     *
5089     * @attr ref android.R.styleable#View_nextFocusLeft
5090     */
5091    public void setNextFocusLeftId(int nextFocusLeftId) {
5092        mNextFocusLeftId = nextFocusLeftId;
5093    }
5094
5095    /**
5096     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5097     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5098     *
5099     * @attr ref android.R.styleable#View_nextFocusRight
5100     */
5101    public int getNextFocusRightId() {
5102        return mNextFocusRightId;
5103    }
5104
5105    /**
5106     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5107     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5108     * decide automatically.
5109     *
5110     * @attr ref android.R.styleable#View_nextFocusRight
5111     */
5112    public void setNextFocusRightId(int nextFocusRightId) {
5113        mNextFocusRightId = nextFocusRightId;
5114    }
5115
5116    /**
5117     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5118     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5119     *
5120     * @attr ref android.R.styleable#View_nextFocusUp
5121     */
5122    public int getNextFocusUpId() {
5123        return mNextFocusUpId;
5124    }
5125
5126    /**
5127     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5128     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5129     * decide automatically.
5130     *
5131     * @attr ref android.R.styleable#View_nextFocusUp
5132     */
5133    public void setNextFocusUpId(int nextFocusUpId) {
5134        mNextFocusUpId = nextFocusUpId;
5135    }
5136
5137    /**
5138     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5139     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5140     *
5141     * @attr ref android.R.styleable#View_nextFocusDown
5142     */
5143    public int getNextFocusDownId() {
5144        return mNextFocusDownId;
5145    }
5146
5147    /**
5148     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5149     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5150     * decide automatically.
5151     *
5152     * @attr ref android.R.styleable#View_nextFocusDown
5153     */
5154    public void setNextFocusDownId(int nextFocusDownId) {
5155        mNextFocusDownId = nextFocusDownId;
5156    }
5157
5158    /**
5159     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5160     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5161     *
5162     * @attr ref android.R.styleable#View_nextFocusForward
5163     */
5164    public int getNextFocusForwardId() {
5165        return mNextFocusForwardId;
5166    }
5167
5168    /**
5169     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5170     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5171     * decide automatically.
5172     *
5173     * @attr ref android.R.styleable#View_nextFocusForward
5174     */
5175    public void setNextFocusForwardId(int nextFocusForwardId) {
5176        mNextFocusForwardId = nextFocusForwardId;
5177    }
5178
5179    /**
5180     * Returns the visibility of this view and all of its ancestors
5181     *
5182     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5183     */
5184    public boolean isShown() {
5185        View current = this;
5186        //noinspection ConstantConditions
5187        do {
5188            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5189                return false;
5190            }
5191            ViewParent parent = current.mParent;
5192            if (parent == null) {
5193                return false; // We are not attached to the view root
5194            }
5195            if (!(parent instanceof View)) {
5196                return true;
5197            }
5198            current = (View) parent;
5199        } while (current != null);
5200
5201        return false;
5202    }
5203
5204    /**
5205     * Called by the view hierarchy when the content insets for a window have
5206     * changed, to allow it to adjust its content to fit within those windows.
5207     * The content insets tell you the space that the status bar, input method,
5208     * and other system windows infringe on the application's window.
5209     *
5210     * <p>You do not normally need to deal with this function, since the default
5211     * window decoration given to applications takes care of applying it to the
5212     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5213     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5214     * and your content can be placed under those system elements.  You can then
5215     * use this method within your view hierarchy if you have parts of your UI
5216     * which you would like to ensure are not being covered.
5217     *
5218     * <p>The default implementation of this method simply applies the content
5219     * inset's to the view's padding, consuming that content (modifying the
5220     * insets to be 0), and returning true.  This behavior is off by default, but can
5221     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5222     *
5223     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5224     * insets object is propagated down the hierarchy, so any changes made to it will
5225     * be seen by all following views (including potentially ones above in
5226     * the hierarchy since this is a depth-first traversal).  The first view
5227     * that returns true will abort the entire traversal.
5228     *
5229     * <p>The default implementation works well for a situation where it is
5230     * used with a container that covers the entire window, allowing it to
5231     * apply the appropriate insets to its content on all edges.  If you need
5232     * a more complicated layout (such as two different views fitting system
5233     * windows, one on the top of the window, and one on the bottom),
5234     * you can override the method and handle the insets however you would like.
5235     * Note that the insets provided by the framework are always relative to the
5236     * far edges of the window, not accounting for the location of the called view
5237     * within that window.  (In fact when this method is called you do not yet know
5238     * where the layout will place the view, as it is done before layout happens.)
5239     *
5240     * <p>Note: unlike many View methods, there is no dispatch phase to this
5241     * call.  If you are overriding it in a ViewGroup and want to allow the
5242     * call to continue to your children, you must be sure to call the super
5243     * implementation.
5244     *
5245     * <p>Here is a sample layout that makes use of fitting system windows
5246     * to have controls for a video view placed inside of the window decorations
5247     * that it hides and shows.  This can be used with code like the second
5248     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5249     *
5250     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5251     *
5252     * @param insets Current content insets of the window.  Prior to
5253     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5254     * the insets or else you and Android will be unhappy.
5255     *
5256     * @return Return true if this view applied the insets and it should not
5257     * continue propagating further down the hierarchy, false otherwise.
5258     * @see #getFitsSystemWindows()
5259     * @see #setFitsSystemWindows(boolean)
5260     * @see #setSystemUiVisibility(int)
5261     */
5262    protected boolean fitSystemWindows(Rect insets) {
5263        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5264            mUserPaddingStart = -1;
5265            mUserPaddingEnd = -1;
5266            mUserPaddingRelative = false;
5267            if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5268                    || mAttachInfo == null
5269                    || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) {
5270                internalSetPadding(insets.left, insets.top, insets.right, insets.bottom);
5271                return true;
5272            } else {
5273                internalSetPadding(0, 0, 0, 0);
5274                return false;
5275            }
5276        }
5277        return false;
5278    }
5279
5280    /**
5281     * Sets whether or not this view should account for system screen decorations
5282     * such as the status bar and inset its content; that is, controlling whether
5283     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5284     * executed.  See that method for more details.
5285     *
5286     * <p>Note that if you are providing your own implementation of
5287     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5288     * flag to true -- your implementation will be overriding the default
5289     * implementation that checks this flag.
5290     *
5291     * @param fitSystemWindows If true, then the default implementation of
5292     * {@link #fitSystemWindows(Rect)} will be executed.
5293     *
5294     * @attr ref android.R.styleable#View_fitsSystemWindows
5295     * @see #getFitsSystemWindows()
5296     * @see #fitSystemWindows(Rect)
5297     * @see #setSystemUiVisibility(int)
5298     */
5299    public void setFitsSystemWindows(boolean fitSystemWindows) {
5300        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5301    }
5302
5303    /**
5304     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5305     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5306     * will be executed.
5307     *
5308     * @return Returns true if the default implementation of
5309     * {@link #fitSystemWindows(Rect)} will be executed.
5310     *
5311     * @attr ref android.R.styleable#View_fitsSystemWindows
5312     * @see #setFitsSystemWindows()
5313     * @see #fitSystemWindows(Rect)
5314     * @see #setSystemUiVisibility(int)
5315     */
5316    public boolean getFitsSystemWindows() {
5317        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5318    }
5319
5320    /** @hide */
5321    public boolean fitsSystemWindows() {
5322        return getFitsSystemWindows();
5323    }
5324
5325    /**
5326     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5327     */
5328    public void requestFitSystemWindows() {
5329        if (mParent != null) {
5330            mParent.requestFitSystemWindows();
5331        }
5332    }
5333
5334    /**
5335     * For use by PhoneWindow to make its own system window fitting optional.
5336     * @hide
5337     */
5338    public void makeOptionalFitsSystemWindows() {
5339        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5340    }
5341
5342    /**
5343     * Returns the visibility status for this view.
5344     *
5345     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5346     * @attr ref android.R.styleable#View_visibility
5347     */
5348    @ViewDebug.ExportedProperty(mapping = {
5349        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5350        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5351        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5352    })
5353    public int getVisibility() {
5354        return mViewFlags & VISIBILITY_MASK;
5355    }
5356
5357    /**
5358     * Set the enabled state of this view.
5359     *
5360     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5361     * @attr ref android.R.styleable#View_visibility
5362     */
5363    @RemotableViewMethod
5364    public void setVisibility(int visibility) {
5365        setFlags(visibility, VISIBILITY_MASK);
5366        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5367    }
5368
5369    /**
5370     * Returns the enabled status for this view. The interpretation of the
5371     * enabled state varies by subclass.
5372     *
5373     * @return True if this view is enabled, false otherwise.
5374     */
5375    @ViewDebug.ExportedProperty
5376    public boolean isEnabled() {
5377        return (mViewFlags & ENABLED_MASK) == ENABLED;
5378    }
5379
5380    /**
5381     * Set the enabled state of this view. The interpretation of the enabled
5382     * state varies by subclass.
5383     *
5384     * @param enabled True if this view is enabled, false otherwise.
5385     */
5386    @RemotableViewMethod
5387    public void setEnabled(boolean enabled) {
5388        if (enabled == isEnabled()) return;
5389
5390        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5391
5392        /*
5393         * The View most likely has to change its appearance, so refresh
5394         * the drawable state.
5395         */
5396        refreshDrawableState();
5397
5398        // Invalidate too, since the default behavior for views is to be
5399        // be drawn at 50% alpha rather than to change the drawable.
5400        invalidate(true);
5401    }
5402
5403    /**
5404     * Set whether this view can receive the focus.
5405     *
5406     * Setting this to false will also ensure that this view is not focusable
5407     * in touch mode.
5408     *
5409     * @param focusable If true, this view can receive the focus.
5410     *
5411     * @see #setFocusableInTouchMode(boolean)
5412     * @attr ref android.R.styleable#View_focusable
5413     */
5414    public void setFocusable(boolean focusable) {
5415        if (!focusable) {
5416            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5417        }
5418        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5419    }
5420
5421    /**
5422     * Set whether this view can receive focus while in touch mode.
5423     *
5424     * Setting this to true will also ensure that this view is focusable.
5425     *
5426     * @param focusableInTouchMode If true, this view can receive the focus while
5427     *   in touch mode.
5428     *
5429     * @see #setFocusable(boolean)
5430     * @attr ref android.R.styleable#View_focusableInTouchMode
5431     */
5432    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5433        // Focusable in touch mode should always be set before the focusable flag
5434        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5435        // which, in touch mode, will not successfully request focus on this view
5436        // because the focusable in touch mode flag is not set
5437        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5438        if (focusableInTouchMode) {
5439            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5440        }
5441    }
5442
5443    /**
5444     * Set whether this view should have sound effects enabled for events such as
5445     * clicking and touching.
5446     *
5447     * <p>You may wish to disable sound effects for a view if you already play sounds,
5448     * for instance, a dial key that plays dtmf tones.
5449     *
5450     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5451     * @see #isSoundEffectsEnabled()
5452     * @see #playSoundEffect(int)
5453     * @attr ref android.R.styleable#View_soundEffectsEnabled
5454     */
5455    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5456        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5457    }
5458
5459    /**
5460     * @return whether this view should have sound effects enabled for events such as
5461     *     clicking and touching.
5462     *
5463     * @see #setSoundEffectsEnabled(boolean)
5464     * @see #playSoundEffect(int)
5465     * @attr ref android.R.styleable#View_soundEffectsEnabled
5466     */
5467    @ViewDebug.ExportedProperty
5468    public boolean isSoundEffectsEnabled() {
5469        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5470    }
5471
5472    /**
5473     * Set whether this view should have haptic feedback for events such as
5474     * long presses.
5475     *
5476     * <p>You may wish to disable haptic feedback if your view already controls
5477     * its own haptic feedback.
5478     *
5479     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5480     * @see #isHapticFeedbackEnabled()
5481     * @see #performHapticFeedback(int)
5482     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5483     */
5484    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5485        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5486    }
5487
5488    /**
5489     * @return whether this view should have haptic feedback enabled for events
5490     * long presses.
5491     *
5492     * @see #setHapticFeedbackEnabled(boolean)
5493     * @see #performHapticFeedback(int)
5494     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5495     */
5496    @ViewDebug.ExportedProperty
5497    public boolean isHapticFeedbackEnabled() {
5498        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5499    }
5500
5501    /**
5502     * Returns the layout direction for this view.
5503     *
5504     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5505     *   {@link #LAYOUT_DIRECTION_RTL},
5506     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5507     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5508     * @attr ref android.R.styleable#View_layoutDirection
5509     */
5510    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5511        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5512        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5513        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5514        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5515    })
5516    public int getLayoutDirection() {
5517        return (mPrivateFlags2 & LAYOUT_DIRECTION_MASK) >> LAYOUT_DIRECTION_MASK_SHIFT;
5518    }
5519
5520    /**
5521     * Set the layout direction for this view. This will propagate a reset of layout direction
5522     * resolution to the view's children and resolve layout direction for this view.
5523     *
5524     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
5525     *   {@link #LAYOUT_DIRECTION_RTL},
5526     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5527     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5528     *
5529     * @attr ref android.R.styleable#View_layoutDirection
5530     */
5531    @RemotableViewMethod
5532    public void setLayoutDirection(int layoutDirection) {
5533        if (getLayoutDirection() != layoutDirection) {
5534            // Reset the current layout direction and the resolved one
5535            mPrivateFlags2 &= ~LAYOUT_DIRECTION_MASK;
5536            resetResolvedLayoutDirection();
5537            // Set the new layout direction (filtered) and ask for a layout pass
5538            mPrivateFlags2 |=
5539                    ((layoutDirection << LAYOUT_DIRECTION_MASK_SHIFT) & LAYOUT_DIRECTION_MASK);
5540            requestLayout();
5541        }
5542    }
5543
5544    /**
5545     * Returns the resolved layout direction for this view.
5546     *
5547     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
5548     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
5549     */
5550    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5551        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
5552        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
5553    })
5554    public int getResolvedLayoutDirection() {
5555        // The layout direction will be resolved only if needed
5556        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) != LAYOUT_DIRECTION_RESOLVED) {
5557            resolveLayoutDirection();
5558        }
5559        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
5560                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
5561    }
5562
5563    /**
5564     * Indicates whether or not this view's layout is right-to-left. This is resolved from
5565     * layout attribute and/or the inherited value from the parent
5566     *
5567     * @return true if the layout is right-to-left.
5568     */
5569    @ViewDebug.ExportedProperty(category = "layout")
5570    public boolean isLayoutRtl() {
5571        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
5572    }
5573
5574    /**
5575     * Indicates whether the view is currently tracking transient state that the
5576     * app should not need to concern itself with saving and restoring, but that
5577     * the framework should take special note to preserve when possible.
5578     *
5579     * <p>A view with transient state cannot be trivially rebound from an external
5580     * data source, such as an adapter binding item views in a list. This may be
5581     * because the view is performing an animation, tracking user selection
5582     * of content, or similar.</p>
5583     *
5584     * @return true if the view has transient state
5585     */
5586    @ViewDebug.ExportedProperty(category = "layout")
5587    public boolean hasTransientState() {
5588        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
5589    }
5590
5591    /**
5592     * Set whether this view is currently tracking transient state that the
5593     * framework should attempt to preserve when possible. This flag is reference counted,
5594     * so every call to setHasTransientState(true) should be paired with a later call
5595     * to setHasTransientState(false).
5596     *
5597     * <p>A view with transient state cannot be trivially rebound from an external
5598     * data source, such as an adapter binding item views in a list. This may be
5599     * because the view is performing an animation, tracking user selection
5600     * of content, or similar.</p>
5601     *
5602     * @param hasTransientState true if this view has transient state
5603     */
5604    public void setHasTransientState(boolean hasTransientState) {
5605        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
5606                mTransientStateCount - 1;
5607        if (mTransientStateCount < 0) {
5608            mTransientStateCount = 0;
5609            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
5610                    "unmatched pair of setHasTransientState calls");
5611        }
5612        if ((hasTransientState && mTransientStateCount == 1) ||
5613                (!hasTransientState && mTransientStateCount == 0)) {
5614            // update flag if we've just incremented up from 0 or decremented down to 0
5615            mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
5616                    (hasTransientState ? HAS_TRANSIENT_STATE : 0);
5617            if (mParent != null) {
5618                try {
5619                    mParent.childHasTransientStateChanged(this, hasTransientState);
5620                } catch (AbstractMethodError e) {
5621                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
5622                            " does not fully implement ViewParent", e);
5623                }
5624            }
5625        }
5626    }
5627
5628    /**
5629     * If this view doesn't do any drawing on its own, set this flag to
5630     * allow further optimizations. By default, this flag is not set on
5631     * View, but could be set on some View subclasses such as ViewGroup.
5632     *
5633     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
5634     * you should clear this flag.
5635     *
5636     * @param willNotDraw whether or not this View draw on its own
5637     */
5638    public void setWillNotDraw(boolean willNotDraw) {
5639        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
5640    }
5641
5642    /**
5643     * Returns whether or not this View draws on its own.
5644     *
5645     * @return true if this view has nothing to draw, false otherwise
5646     */
5647    @ViewDebug.ExportedProperty(category = "drawing")
5648    public boolean willNotDraw() {
5649        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
5650    }
5651
5652    /**
5653     * When a View's drawing cache is enabled, drawing is redirected to an
5654     * offscreen bitmap. Some views, like an ImageView, must be able to
5655     * bypass this mechanism if they already draw a single bitmap, to avoid
5656     * unnecessary usage of the memory.
5657     *
5658     * @param willNotCacheDrawing true if this view does not cache its
5659     *        drawing, false otherwise
5660     */
5661    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5662        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5663    }
5664
5665    /**
5666     * Returns whether or not this View can cache its drawing or not.
5667     *
5668     * @return true if this view does not cache its drawing, false otherwise
5669     */
5670    @ViewDebug.ExportedProperty(category = "drawing")
5671    public boolean willNotCacheDrawing() {
5672        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5673    }
5674
5675    /**
5676     * Indicates whether this view reacts to click events or not.
5677     *
5678     * @return true if the view is clickable, false otherwise
5679     *
5680     * @see #setClickable(boolean)
5681     * @attr ref android.R.styleable#View_clickable
5682     */
5683    @ViewDebug.ExportedProperty
5684    public boolean isClickable() {
5685        return (mViewFlags & CLICKABLE) == CLICKABLE;
5686    }
5687
5688    /**
5689     * Enables or disables click events for this view. When a view
5690     * is clickable it will change its state to "pressed" on every click.
5691     * Subclasses should set the view clickable to visually react to
5692     * user's clicks.
5693     *
5694     * @param clickable true to make the view clickable, false otherwise
5695     *
5696     * @see #isClickable()
5697     * @attr ref android.R.styleable#View_clickable
5698     */
5699    public void setClickable(boolean clickable) {
5700        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5701    }
5702
5703    /**
5704     * Indicates whether this view reacts to long click events or not.
5705     *
5706     * @return true if the view is long clickable, false otherwise
5707     *
5708     * @see #setLongClickable(boolean)
5709     * @attr ref android.R.styleable#View_longClickable
5710     */
5711    public boolean isLongClickable() {
5712        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5713    }
5714
5715    /**
5716     * Enables or disables long click events for this view. When a view is long
5717     * clickable it reacts to the user holding down the button for a longer
5718     * duration than a tap. This event can either launch the listener or a
5719     * context menu.
5720     *
5721     * @param longClickable true to make the view long clickable, false otherwise
5722     * @see #isLongClickable()
5723     * @attr ref android.R.styleable#View_longClickable
5724     */
5725    public void setLongClickable(boolean longClickable) {
5726        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5727    }
5728
5729    /**
5730     * Sets the pressed state for this view.
5731     *
5732     * @see #isClickable()
5733     * @see #setClickable(boolean)
5734     *
5735     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5736     *        the View's internal state from a previously set "pressed" state.
5737     */
5738    public void setPressed(boolean pressed) {
5739        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5740
5741        if (pressed) {
5742            mPrivateFlags |= PRESSED;
5743        } else {
5744            mPrivateFlags &= ~PRESSED;
5745        }
5746
5747        if (needsRefresh) {
5748            refreshDrawableState();
5749        }
5750        dispatchSetPressed(pressed);
5751    }
5752
5753    /**
5754     * Dispatch setPressed to all of this View's children.
5755     *
5756     * @see #setPressed(boolean)
5757     *
5758     * @param pressed The new pressed state
5759     */
5760    protected void dispatchSetPressed(boolean pressed) {
5761    }
5762
5763    /**
5764     * Indicates whether the view is currently in pressed state. Unless
5765     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5766     * the pressed state.
5767     *
5768     * @see #setPressed(boolean)
5769     * @see #isClickable()
5770     * @see #setClickable(boolean)
5771     *
5772     * @return true if the view is currently pressed, false otherwise
5773     */
5774    public boolean isPressed() {
5775        return (mPrivateFlags & PRESSED) == PRESSED;
5776    }
5777
5778    /**
5779     * Indicates whether this view will save its state (that is,
5780     * whether its {@link #onSaveInstanceState} method will be called).
5781     *
5782     * @return Returns true if the view state saving is enabled, else false.
5783     *
5784     * @see #setSaveEnabled(boolean)
5785     * @attr ref android.R.styleable#View_saveEnabled
5786     */
5787    public boolean isSaveEnabled() {
5788        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5789    }
5790
5791    /**
5792     * Controls whether the saving of this view's state is
5793     * enabled (that is, whether its {@link #onSaveInstanceState} method
5794     * will be called).  Note that even if freezing is enabled, the
5795     * view still must have an id assigned to it (via {@link #setId(int)})
5796     * for its state to be saved.  This flag can only disable the
5797     * saving of this view; any child views may still have their state saved.
5798     *
5799     * @param enabled Set to false to <em>disable</em> state saving, or true
5800     * (the default) to allow it.
5801     *
5802     * @see #isSaveEnabled()
5803     * @see #setId(int)
5804     * @see #onSaveInstanceState()
5805     * @attr ref android.R.styleable#View_saveEnabled
5806     */
5807    public void setSaveEnabled(boolean enabled) {
5808        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5809    }
5810
5811    /**
5812     * Gets whether the framework should discard touches when the view's
5813     * window is obscured by another visible window.
5814     * Refer to the {@link View} security documentation for more details.
5815     *
5816     * @return True if touch filtering is enabled.
5817     *
5818     * @see #setFilterTouchesWhenObscured(boolean)
5819     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5820     */
5821    @ViewDebug.ExportedProperty
5822    public boolean getFilterTouchesWhenObscured() {
5823        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5824    }
5825
5826    /**
5827     * Sets whether the framework should discard touches when the view's
5828     * window is obscured by another visible window.
5829     * Refer to the {@link View} security documentation for more details.
5830     *
5831     * @param enabled True if touch filtering should be enabled.
5832     *
5833     * @see #getFilterTouchesWhenObscured
5834     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5835     */
5836    public void setFilterTouchesWhenObscured(boolean enabled) {
5837        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5838                FILTER_TOUCHES_WHEN_OBSCURED);
5839    }
5840
5841    /**
5842     * Indicates whether the entire hierarchy under this view will save its
5843     * state when a state saving traversal occurs from its parent.  The default
5844     * is true; if false, these views will not be saved unless
5845     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5846     *
5847     * @return Returns true if the view state saving from parent is enabled, else false.
5848     *
5849     * @see #setSaveFromParentEnabled(boolean)
5850     */
5851    public boolean isSaveFromParentEnabled() {
5852        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5853    }
5854
5855    /**
5856     * Controls whether the entire hierarchy under this view will save its
5857     * state when a state saving traversal occurs from its parent.  The default
5858     * is true; if false, these views will not be saved unless
5859     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5860     *
5861     * @param enabled Set to false to <em>disable</em> state saving, or true
5862     * (the default) to allow it.
5863     *
5864     * @see #isSaveFromParentEnabled()
5865     * @see #setId(int)
5866     * @see #onSaveInstanceState()
5867     */
5868    public void setSaveFromParentEnabled(boolean enabled) {
5869        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5870    }
5871
5872
5873    /**
5874     * Returns whether this View is able to take focus.
5875     *
5876     * @return True if this view can take focus, or false otherwise.
5877     * @attr ref android.R.styleable#View_focusable
5878     */
5879    @ViewDebug.ExportedProperty(category = "focus")
5880    public final boolean isFocusable() {
5881        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5882    }
5883
5884    /**
5885     * When a view is focusable, it may not want to take focus when in touch mode.
5886     * For example, a button would like focus when the user is navigating via a D-pad
5887     * so that the user can click on it, but once the user starts touching the screen,
5888     * the button shouldn't take focus
5889     * @return Whether the view is focusable in touch mode.
5890     * @attr ref android.R.styleable#View_focusableInTouchMode
5891     */
5892    @ViewDebug.ExportedProperty
5893    public final boolean isFocusableInTouchMode() {
5894        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5895    }
5896
5897    /**
5898     * Find the nearest view in the specified direction that can take focus.
5899     * This does not actually give focus to that view.
5900     *
5901     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5902     *
5903     * @return The nearest focusable in the specified direction, or null if none
5904     *         can be found.
5905     */
5906    public View focusSearch(int direction) {
5907        if (mParent != null) {
5908            return mParent.focusSearch(this, direction);
5909        } else {
5910            return null;
5911        }
5912    }
5913
5914    /**
5915     * This method is the last chance for the focused view and its ancestors to
5916     * respond to an arrow key. This is called when the focused view did not
5917     * consume the key internally, nor could the view system find a new view in
5918     * the requested direction to give focus to.
5919     *
5920     * @param focused The currently focused view.
5921     * @param direction The direction focus wants to move. One of FOCUS_UP,
5922     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5923     * @return True if the this view consumed this unhandled move.
5924     */
5925    public boolean dispatchUnhandledMove(View focused, int direction) {
5926        return false;
5927    }
5928
5929    /**
5930     * If a user manually specified the next view id for a particular direction,
5931     * use the root to look up the view.
5932     * @param root The root view of the hierarchy containing this view.
5933     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5934     * or FOCUS_BACKWARD.
5935     * @return The user specified next view, or null if there is none.
5936     */
5937    View findUserSetNextFocus(View root, int direction) {
5938        switch (direction) {
5939            case FOCUS_LEFT:
5940                if (mNextFocusLeftId == View.NO_ID) return null;
5941                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5942            case FOCUS_RIGHT:
5943                if (mNextFocusRightId == View.NO_ID) return null;
5944                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5945            case FOCUS_UP:
5946                if (mNextFocusUpId == View.NO_ID) return null;
5947                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5948            case FOCUS_DOWN:
5949                if (mNextFocusDownId == View.NO_ID) return null;
5950                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5951            case FOCUS_FORWARD:
5952                if (mNextFocusForwardId == View.NO_ID) return null;
5953                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5954            case FOCUS_BACKWARD: {
5955                if (mID == View.NO_ID) return null;
5956                final int id = mID;
5957                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5958                    @Override
5959                    public boolean apply(View t) {
5960                        return t.mNextFocusForwardId == id;
5961                    }
5962                });
5963            }
5964        }
5965        return null;
5966    }
5967
5968    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5969        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5970            @Override
5971            public boolean apply(View t) {
5972                return t.mID == childViewId;
5973            }
5974        });
5975
5976        if (result == null) {
5977            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5978                    + "by user for id " + childViewId);
5979        }
5980        return result;
5981    }
5982
5983    /**
5984     * Find and return all focusable views that are descendants of this view,
5985     * possibly including this view if it is focusable itself.
5986     *
5987     * @param direction The direction of the focus
5988     * @return A list of focusable views
5989     */
5990    public ArrayList<View> getFocusables(int direction) {
5991        ArrayList<View> result = new ArrayList<View>(24);
5992        addFocusables(result, direction);
5993        return result;
5994    }
5995
5996    /**
5997     * Add any focusable views that are descendants of this view (possibly
5998     * including this view if it is focusable itself) to views.  If we are in touch mode,
5999     * only add views that are also focusable in touch mode.
6000     *
6001     * @param views Focusable views found so far
6002     * @param direction The direction of the focus
6003     */
6004    public void addFocusables(ArrayList<View> views, int direction) {
6005        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6006    }
6007
6008    /**
6009     * Adds any focusable views that are descendants of this view (possibly
6010     * including this view if it is focusable itself) to views. This method
6011     * adds all focusable views regardless if we are in touch mode or
6012     * only views focusable in touch mode if we are in touch mode or
6013     * only views that can take accessibility focus if accessibility is enabeld
6014     * depending on the focusable mode paramater.
6015     *
6016     * @param views Focusable views found so far or null if all we are interested is
6017     *        the number of focusables.
6018     * @param direction The direction of the focus.
6019     * @param focusableMode The type of focusables to be added.
6020     *
6021     * @see #FOCUSABLES_ALL
6022     * @see #FOCUSABLES_TOUCH_MODE
6023     */
6024    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6025        if (views == null) {
6026            return;
6027        }
6028        if (!isFocusable()) {
6029            return;
6030        }
6031        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6032                && isInTouchMode() && !isFocusableInTouchMode()) {
6033            return;
6034        }
6035        views.add(this);
6036    }
6037
6038    /**
6039     * Finds the Views that contain given text. The containment is case insensitive.
6040     * The search is performed by either the text that the View renders or the content
6041     * description that describes the view for accessibility purposes and the view does
6042     * not render or both. Clients can specify how the search is to be performed via
6043     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6044     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6045     *
6046     * @param outViews The output list of matching Views.
6047     * @param searched The text to match against.
6048     *
6049     * @see #FIND_VIEWS_WITH_TEXT
6050     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6051     * @see #setContentDescription(CharSequence)
6052     */
6053    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6054        if (getAccessibilityNodeProvider() != null) {
6055            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6056                outViews.add(this);
6057            }
6058        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6059                && (searched != null && searched.length() > 0)
6060                && (mContentDescription != null && mContentDescription.length() > 0)) {
6061            String searchedLowerCase = searched.toString().toLowerCase();
6062            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6063            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6064                outViews.add(this);
6065            }
6066        }
6067    }
6068
6069    /**
6070     * Find and return all touchable views that are descendants of this view,
6071     * possibly including this view if it is touchable itself.
6072     *
6073     * @return A list of touchable views
6074     */
6075    public ArrayList<View> getTouchables() {
6076        ArrayList<View> result = new ArrayList<View>();
6077        addTouchables(result);
6078        return result;
6079    }
6080
6081    /**
6082     * Add any touchable views that are descendants of this view (possibly
6083     * including this view if it is touchable itself) to views.
6084     *
6085     * @param views Touchable views found so far
6086     */
6087    public void addTouchables(ArrayList<View> views) {
6088        final int viewFlags = mViewFlags;
6089
6090        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6091                && (viewFlags & ENABLED_MASK) == ENABLED) {
6092            views.add(this);
6093        }
6094    }
6095
6096    /**
6097     * Returns whether this View is accessibility focused.
6098     *
6099     * @return True if this View is accessibility focused.
6100     */
6101    boolean isAccessibilityFocused() {
6102        return (mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0;
6103    }
6104
6105    /**
6106     * Call this to try to give accessibility focus to this view.
6107     *
6108     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6109     * returns false or the view is no visible or the view already has accessibility
6110     * focus.
6111     *
6112     * See also {@link #focusSearch(int)}, which is what you call to say that you
6113     * have focus, and you want your parent to look for the next one.
6114     *
6115     * @return Whether this view actually took accessibility focus.
6116     *
6117     * @hide
6118     */
6119    public boolean requestAccessibilityFocus() {
6120        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6121        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6122            return false;
6123        }
6124        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6125            return false;
6126        }
6127        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) == 0) {
6128            mPrivateFlags2 |= ACCESSIBILITY_FOCUSED;
6129            ViewRootImpl viewRootImpl = getViewRootImpl();
6130            if (viewRootImpl != null) {
6131                viewRootImpl.setAccessibilityFocus(this, null);
6132            }
6133            invalidate();
6134            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6135            notifyAccessibilityStateChanged();
6136            return true;
6137        }
6138        return false;
6139    }
6140
6141    /**
6142     * Call this to try to clear accessibility focus of this view.
6143     *
6144     * See also {@link #focusSearch(int)}, which is what you call to say that you
6145     * have focus, and you want your parent to look for the next one.
6146     *
6147     * @hide
6148     */
6149    public void clearAccessibilityFocus() {
6150        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6151            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6152            invalidate();
6153            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6154            notifyAccessibilityStateChanged();
6155        }
6156        // Clear the global reference of accessibility focus if this
6157        // view or any of its descendants had accessibility focus.
6158        ViewRootImpl viewRootImpl = getViewRootImpl();
6159        if (viewRootImpl != null) {
6160            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6161            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6162                viewRootImpl.setAccessibilityFocus(null, null);
6163            }
6164        }
6165    }
6166
6167    private void sendAccessibilityHoverEvent(int eventType) {
6168        // Since we are not delivering to a client accessibility events from not
6169        // important views (unless the clinet request that) we need to fire the
6170        // event from the deepest view exposed to the client. As a consequence if
6171        // the user crosses a not exposed view the client will see enter and exit
6172        // of the exposed predecessor followed by and enter and exit of that same
6173        // predecessor when entering and exiting the not exposed descendant. This
6174        // is fine since the client has a clear idea which view is hovered at the
6175        // price of a couple more events being sent. This is a simple and
6176        // working solution.
6177        View source = this;
6178        while (true) {
6179            if (source.includeForAccessibility()) {
6180                source.sendAccessibilityEvent(eventType);
6181                return;
6182            }
6183            ViewParent parent = source.getParent();
6184            if (parent instanceof View) {
6185                source = (View) parent;
6186            } else {
6187                return;
6188            }
6189        }
6190    }
6191
6192    /**
6193     * Clears accessibility focus without calling any callback methods
6194     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6195     * is used for clearing accessibility focus when giving this focus to
6196     * another view.
6197     */
6198    void clearAccessibilityFocusNoCallbacks() {
6199        if ((mPrivateFlags2 & ACCESSIBILITY_FOCUSED) != 0) {
6200            mPrivateFlags2 &= ~ACCESSIBILITY_FOCUSED;
6201            invalidate();
6202        }
6203    }
6204
6205    /**
6206     * Call this to try to give focus to a specific view or to one of its
6207     * descendants.
6208     *
6209     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6210     * false), or if it is focusable and it is not focusable in touch mode
6211     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6212     *
6213     * See also {@link #focusSearch(int)}, which is what you call to say that you
6214     * have focus, and you want your parent to look for the next one.
6215     *
6216     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6217     * {@link #FOCUS_DOWN} and <code>null</code>.
6218     *
6219     * @return Whether this view or one of its descendants actually took focus.
6220     */
6221    public final boolean requestFocus() {
6222        return requestFocus(View.FOCUS_DOWN);
6223    }
6224
6225    /**
6226     * Call this to try to give focus to a specific view or to one of its
6227     * descendants and give it a hint about what direction focus is heading.
6228     *
6229     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6230     * false), or if it is focusable and it is not focusable in touch mode
6231     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6232     *
6233     * See also {@link #focusSearch(int)}, which is what you call to say that you
6234     * have focus, and you want your parent to look for the next one.
6235     *
6236     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6237     * <code>null</code> set for the previously focused rectangle.
6238     *
6239     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6240     * @return Whether this view or one of its descendants actually took focus.
6241     */
6242    public final boolean requestFocus(int direction) {
6243        return requestFocus(direction, null);
6244    }
6245
6246    /**
6247     * Call this to try to give focus to a specific view or to one of its descendants
6248     * and give it hints about the direction and a specific rectangle that the focus
6249     * is coming from.  The rectangle can help give larger views a finer grained hint
6250     * about where focus is coming from, and therefore, where to show selection, or
6251     * forward focus change internally.
6252     *
6253     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6254     * false), or if it is focusable and it is not focusable in touch mode
6255     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6256     *
6257     * A View will not take focus if it is not visible.
6258     *
6259     * A View will not take focus if one of its parents has
6260     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6261     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6262     *
6263     * See also {@link #focusSearch(int)}, which is what you call to say that you
6264     * have focus, and you want your parent to look for the next one.
6265     *
6266     * You may wish to override this method if your custom {@link View} has an internal
6267     * {@link View} that it wishes to forward the request to.
6268     *
6269     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6270     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6271     *        to give a finer grained hint about where focus is coming from.  May be null
6272     *        if there is no hint.
6273     * @return Whether this view or one of its descendants actually took focus.
6274     */
6275    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6276        return requestFocusNoSearch(direction, previouslyFocusedRect);
6277    }
6278
6279    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6280        // need to be focusable
6281        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6282                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6283            return false;
6284        }
6285
6286        // need to be focusable in touch mode if in touch mode
6287        if (isInTouchMode() &&
6288            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6289               return false;
6290        }
6291
6292        // need to not have any parents blocking us
6293        if (hasAncestorThatBlocksDescendantFocus()) {
6294            return false;
6295        }
6296
6297        handleFocusGainInternal(direction, previouslyFocusedRect);
6298        return true;
6299    }
6300
6301    /**
6302     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6303     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6304     * touch mode to request focus when they are touched.
6305     *
6306     * @return Whether this view or one of its descendants actually took focus.
6307     *
6308     * @see #isInTouchMode()
6309     *
6310     */
6311    public final boolean requestFocusFromTouch() {
6312        // Leave touch mode if we need to
6313        if (isInTouchMode()) {
6314            ViewRootImpl viewRoot = getViewRootImpl();
6315            if (viewRoot != null) {
6316                viewRoot.ensureTouchMode(false);
6317            }
6318        }
6319        return requestFocus(View.FOCUS_DOWN);
6320    }
6321
6322    /**
6323     * @return Whether any ancestor of this view blocks descendant focus.
6324     */
6325    private boolean hasAncestorThatBlocksDescendantFocus() {
6326        ViewParent ancestor = mParent;
6327        while (ancestor instanceof ViewGroup) {
6328            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6329            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6330                return true;
6331            } else {
6332                ancestor = vgAncestor.getParent();
6333            }
6334        }
6335        return false;
6336    }
6337
6338    /**
6339     * Gets the mode for determining whether this View is important for accessibility
6340     * which is if it fires accessibility events and if it is reported to
6341     * accessibility services that query the screen.
6342     *
6343     * @return The mode for determining whether a View is important for accessibility.
6344     *
6345     * @attr ref android.R.styleable#View_importantForAccessibility
6346     *
6347     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6348     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6349     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6350     */
6351    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6352            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6353            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6354            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6355        })
6356    public int getImportantForAccessibility() {
6357        return (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6358                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6359    }
6360
6361    /**
6362     * Sets how to determine whether this view is important for accessibility
6363     * which is if it fires accessibility events and if it is reported to
6364     * accessibility services that query the screen.
6365     *
6366     * @param mode How to determine whether this view is important for accessibility.
6367     *
6368     * @attr ref android.R.styleable#View_importantForAccessibility
6369     *
6370     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6371     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6372     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6373     */
6374    public void setImportantForAccessibility(int mode) {
6375        if (mode != getImportantForAccessibility()) {
6376            mPrivateFlags2 &= ~IMPORTANT_FOR_ACCESSIBILITY_MASK;
6377            mPrivateFlags2 |= (mode << IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6378                    & IMPORTANT_FOR_ACCESSIBILITY_MASK;
6379            notifyAccessibilityStateChanged();
6380        }
6381    }
6382
6383    /**
6384     * Gets whether this view should be exposed for accessibility.
6385     *
6386     * @return Whether the view is exposed for accessibility.
6387     *
6388     * @hide
6389     */
6390    public boolean isImportantForAccessibility() {
6391        final int mode = (mPrivateFlags2 & IMPORTANT_FOR_ACCESSIBILITY_MASK)
6392                >> IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6393        switch (mode) {
6394            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6395                return true;
6396            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6397                return false;
6398            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6399                return isActionableForAccessibility() || hasListenersForAccessibility();
6400            default:
6401                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6402                        + mode);
6403        }
6404    }
6405
6406    /**
6407     * Gets the parent for accessibility purposes. Note that the parent for
6408     * accessibility is not necessary the immediate parent. It is the first
6409     * predecessor that is important for accessibility.
6410     *
6411     * @return The parent for accessibility purposes.
6412     */
6413    public ViewParent getParentForAccessibility() {
6414        if (mParent instanceof View) {
6415            View parentView = (View) mParent;
6416            if (parentView.includeForAccessibility()) {
6417                return mParent;
6418            } else {
6419                return mParent.getParentForAccessibility();
6420            }
6421        }
6422        return null;
6423    }
6424
6425    /**
6426     * Adds the children of a given View for accessibility. Since some Views are
6427     * not important for accessibility the children for accessibility are not
6428     * necessarily direct children of the riew, rather they are the first level of
6429     * descendants important for accessibility.
6430     *
6431     * @param children The list of children for accessibility.
6432     */
6433    public void addChildrenForAccessibility(ArrayList<View> children) {
6434        if (includeForAccessibility()) {
6435            children.add(this);
6436        }
6437    }
6438
6439    /**
6440     * Whether to regard this view for accessibility. A view is regarded for
6441     * accessibility if it is important for accessibility or the querying
6442     * accessibility service has explicitly requested that view not
6443     * important for accessibility are regarded.
6444     *
6445     * @return Whether to regard the view for accessibility.
6446     *
6447     * @hide
6448     */
6449    public boolean includeForAccessibility() {
6450        if (mAttachInfo != null) {
6451            return mAttachInfo.mIncludeNotImportantViews || isImportantForAccessibility();
6452        }
6453        return false;
6454    }
6455
6456    /**
6457     * Returns whether the View is considered actionable from
6458     * accessibility perspective. Such view are important for
6459     * accessiiblity.
6460     *
6461     * @return True if the view is actionable for accessibility.
6462     *
6463     * @hide
6464     */
6465    public boolean isActionableForAccessibility() {
6466        return (isClickable() || isLongClickable() || isFocusable());
6467    }
6468
6469    /**
6470     * Returns whether the View has registered callbacks wich makes it
6471     * important for accessiiblity.
6472     *
6473     * @return True if the view is actionable for accessibility.
6474     */
6475    private boolean hasListenersForAccessibility() {
6476        ListenerInfo info = getListenerInfo();
6477        return mTouchDelegate != null || info.mOnKeyListener != null
6478                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6479                || info.mOnHoverListener != null || info.mOnDragListener != null;
6480    }
6481
6482    /**
6483     * Notifies accessibility services that some view's important for
6484     * accessibility state has changed. Note that such notifications
6485     * are made at most once every
6486     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6487     * to avoid unnecessary load to the system. Also once a view has
6488     * made a notifucation this method is a NOP until the notification has
6489     * been sent to clients.
6490     *
6491     * @hide
6492     *
6493     * TODO: Makse sure this method is called for any view state change
6494     *       that is interesting for accessilility purposes.
6495     */
6496    public void notifyAccessibilityStateChanged() {
6497        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6498            return;
6499        }
6500        if ((mPrivateFlags2 & ACCESSIBILITY_STATE_CHANGED) == 0) {
6501            mPrivateFlags2 |= ACCESSIBILITY_STATE_CHANGED;
6502            if (mParent != null) {
6503                mParent.childAccessibilityStateChanged(this);
6504            }
6505        }
6506    }
6507
6508    /**
6509     * Reset the state indicating the this view has requested clients
6510     * interested in its accessiblity state to be notified.
6511     *
6512     * @hide
6513     */
6514    public void resetAccessibilityStateChanged() {
6515        mPrivateFlags2 &= ~ACCESSIBILITY_STATE_CHANGED;
6516    }
6517
6518    /**
6519     * Performs the specified accessibility action on the view. For
6520     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6521    * <p>
6522    * If an {@link AccessibilityDelegate} has been specified via calling
6523    * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6524    * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6525    * is responsible for handling this call.
6526    * </p>
6527     *
6528     * @param action The action to perform.
6529     * @param arguments Optional action arguments.
6530     * @return Whether the action was performed.
6531     */
6532    public boolean performAccessibilityAction(int action, Bundle arguments) {
6533      if (mAccessibilityDelegate != null) {
6534          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6535      } else {
6536          return performAccessibilityActionInternal(action, arguments);
6537      }
6538    }
6539
6540   /**
6541    * @see #performAccessibilityAction(int, Bundle)
6542    *
6543    * Note: Called from the default {@link AccessibilityDelegate}.
6544    */
6545    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
6546        switch (action) {
6547            case AccessibilityNodeInfo.ACTION_CLICK: {
6548                if (isClickable()) {
6549                    return performClick();
6550                }
6551            } break;
6552            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
6553                if (isLongClickable()) {
6554                    return performLongClick();
6555                }
6556            } break;
6557            case AccessibilityNodeInfo.ACTION_FOCUS: {
6558                if (!hasFocus()) {
6559                    // Get out of touch mode since accessibility
6560                    // wants to move focus around.
6561                    getViewRootImpl().ensureTouchMode(false);
6562                    return requestFocus();
6563                }
6564            } break;
6565            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
6566                if (hasFocus()) {
6567                    clearFocus();
6568                    return !isFocused();
6569                }
6570            } break;
6571            case AccessibilityNodeInfo.ACTION_SELECT: {
6572                if (!isSelected()) {
6573                    setSelected(true);
6574                    return isSelected();
6575                }
6576            } break;
6577            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
6578                if (isSelected()) {
6579                    setSelected(false);
6580                    return !isSelected();
6581                }
6582            } break;
6583            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
6584                if (!isAccessibilityFocused()) {
6585                    return requestAccessibilityFocus();
6586                }
6587            } break;
6588            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
6589                if (isAccessibilityFocused()) {
6590                    clearAccessibilityFocus();
6591                    return true;
6592                }
6593            } break;
6594            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
6595                if (arguments != null) {
6596                    final int granularity = arguments.getInt(
6597                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6598                    return nextAtGranularity(granularity);
6599                }
6600            } break;
6601            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
6602                if (arguments != null) {
6603                    final int granularity = arguments.getInt(
6604                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
6605                    return previousAtGranularity(granularity);
6606                }
6607            } break;
6608        }
6609        return false;
6610    }
6611
6612    private boolean nextAtGranularity(int granularity) {
6613        CharSequence text = getIterableTextForAccessibility();
6614        if (text == null || text.length() == 0) {
6615            return false;
6616        }
6617        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6618        if (iterator == null) {
6619            return false;
6620        }
6621        final int current = getAccessibilityCursorPosition();
6622        final int[] range = iterator.following(current);
6623        if (range == null) {
6624            return false;
6625        }
6626        final int start = range[0];
6627        final int end = range[1];
6628        setAccessibilityCursorPosition(end);
6629        sendViewTextTraversedAtGranularityEvent(
6630                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
6631                granularity, start, end);
6632        return true;
6633    }
6634
6635    private boolean previousAtGranularity(int granularity) {
6636        CharSequence text = getIterableTextForAccessibility();
6637        if (text == null || text.length() == 0) {
6638            return false;
6639        }
6640        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
6641        if (iterator == null) {
6642            return false;
6643        }
6644        int current = getAccessibilityCursorPosition();
6645        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
6646            current = text.length();
6647        } else if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6648            // When traversing by character we always put the cursor after the character
6649            // to ease edit and have to compensate before asking the for previous segment.
6650            current--;
6651        }
6652        final int[] range = iterator.preceding(current);
6653        if (range == null) {
6654            return false;
6655        }
6656        final int start = range[0];
6657        final int end = range[1];
6658        // Always put the cursor after the character to ease edit.
6659        if (granularity == AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER) {
6660            setAccessibilityCursorPosition(end);
6661        } else {
6662            setAccessibilityCursorPosition(start);
6663        }
6664        sendViewTextTraversedAtGranularityEvent(
6665                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
6666                granularity, start, end);
6667        return true;
6668    }
6669
6670    /**
6671     * Gets the text reported for accessibility purposes.
6672     *
6673     * @return The accessibility text.
6674     *
6675     * @hide
6676     */
6677    public CharSequence getIterableTextForAccessibility() {
6678        return mContentDescription;
6679    }
6680
6681    /**
6682     * @hide
6683     */
6684    public int getAccessibilityCursorPosition() {
6685        return mAccessibilityCursorPosition;
6686    }
6687
6688    /**
6689     * @hide
6690     */
6691    public void setAccessibilityCursorPosition(int position) {
6692        mAccessibilityCursorPosition = position;
6693    }
6694
6695    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
6696            int fromIndex, int toIndex) {
6697        if (mParent == null) {
6698            return;
6699        }
6700        AccessibilityEvent event = AccessibilityEvent.obtain(
6701                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
6702        onInitializeAccessibilityEvent(event);
6703        onPopulateAccessibilityEvent(event);
6704        event.setFromIndex(fromIndex);
6705        event.setToIndex(toIndex);
6706        event.setAction(action);
6707        event.setMovementGranularity(granularity);
6708        mParent.requestSendAccessibilityEvent(this, event);
6709    }
6710
6711    /**
6712     * @hide
6713     */
6714    public TextSegmentIterator getIteratorForGranularity(int granularity) {
6715        switch (granularity) {
6716            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
6717                CharSequence text = getIterableTextForAccessibility();
6718                if (text != null && text.length() > 0) {
6719                    CharacterTextSegmentIterator iterator =
6720                        CharacterTextSegmentIterator.getInstance(
6721                                mContext.getResources().getConfiguration().locale);
6722                    iterator.initialize(text.toString());
6723                    return iterator;
6724                }
6725            } break;
6726            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
6727                CharSequence text = getIterableTextForAccessibility();
6728                if (text != null && text.length() > 0) {
6729                    WordTextSegmentIterator iterator =
6730                        WordTextSegmentIterator.getInstance(
6731                                mContext.getResources().getConfiguration().locale);
6732                    iterator.initialize(text.toString());
6733                    return iterator;
6734                }
6735            } break;
6736            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
6737                CharSequence text = getIterableTextForAccessibility();
6738                if (text != null && text.length() > 0) {
6739                    ParagraphTextSegmentIterator iterator =
6740                        ParagraphTextSegmentIterator.getInstance();
6741                    iterator.initialize(text.toString());
6742                    return iterator;
6743                }
6744            } break;
6745        }
6746        return null;
6747    }
6748
6749    /**
6750     * @hide
6751     */
6752    public void dispatchStartTemporaryDetach() {
6753        clearAccessibilityFocus();
6754        clearDisplayList();
6755
6756        onStartTemporaryDetach();
6757    }
6758
6759    /**
6760     * This is called when a container is going to temporarily detach a child, with
6761     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
6762     * It will either be followed by {@link #onFinishTemporaryDetach()} or
6763     * {@link #onDetachedFromWindow()} when the container is done.
6764     */
6765    public void onStartTemporaryDetach() {
6766        removeUnsetPressCallback();
6767        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
6768    }
6769
6770    /**
6771     * @hide
6772     */
6773    public void dispatchFinishTemporaryDetach() {
6774        onFinishTemporaryDetach();
6775    }
6776
6777    /**
6778     * Called after {@link #onStartTemporaryDetach} when the container is done
6779     * changing the view.
6780     */
6781    public void onFinishTemporaryDetach() {
6782    }
6783
6784    /**
6785     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
6786     * for this view's window.  Returns null if the view is not currently attached
6787     * to the window.  Normally you will not need to use this directly, but
6788     * just use the standard high-level event callbacks like
6789     * {@link #onKeyDown(int, KeyEvent)}.
6790     */
6791    public KeyEvent.DispatcherState getKeyDispatcherState() {
6792        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
6793    }
6794
6795    /**
6796     * Dispatch a key event before it is processed by any input method
6797     * associated with the view hierarchy.  This can be used to intercept
6798     * key events in special situations before the IME consumes them; a
6799     * typical example would be handling the BACK key to update the application's
6800     * UI instead of allowing the IME to see it and close itself.
6801     *
6802     * @param event The key event to be dispatched.
6803     * @return True if the event was handled, false otherwise.
6804     */
6805    public boolean dispatchKeyEventPreIme(KeyEvent event) {
6806        return onKeyPreIme(event.getKeyCode(), event);
6807    }
6808
6809    /**
6810     * Dispatch a key event to the next view on the focus path. This path runs
6811     * from the top of the view tree down to the currently focused view. If this
6812     * view has focus, it will dispatch to itself. Otherwise it will dispatch
6813     * the next node down the focus path. This method also fires any key
6814     * listeners.
6815     *
6816     * @param event The key event to be dispatched.
6817     * @return True if the event was handled, false otherwise.
6818     */
6819    public boolean dispatchKeyEvent(KeyEvent event) {
6820        if (mInputEventConsistencyVerifier != null) {
6821            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
6822        }
6823
6824        // Give any attached key listener a first crack at the event.
6825        //noinspection SimplifiableIfStatement
6826        ListenerInfo li = mListenerInfo;
6827        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6828                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
6829            return true;
6830        }
6831
6832        if (event.dispatch(this, mAttachInfo != null
6833                ? mAttachInfo.mKeyDispatchState : null, this)) {
6834            return true;
6835        }
6836
6837        if (mInputEventConsistencyVerifier != null) {
6838            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6839        }
6840        return false;
6841    }
6842
6843    /**
6844     * Dispatches a key shortcut event.
6845     *
6846     * @param event The key event to be dispatched.
6847     * @return True if the event was handled by the view, false otherwise.
6848     */
6849    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6850        return onKeyShortcut(event.getKeyCode(), event);
6851    }
6852
6853    /**
6854     * Pass the touch screen motion event down to the target view, or this
6855     * view if it is the target.
6856     *
6857     * @param event The motion event to be dispatched.
6858     * @return True if the event was handled by the view, false otherwise.
6859     */
6860    public boolean dispatchTouchEvent(MotionEvent event) {
6861        if (mInputEventConsistencyVerifier != null) {
6862            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
6863        }
6864
6865        if (onFilterTouchEventForSecurity(event)) {
6866            //noinspection SimplifiableIfStatement
6867            ListenerInfo li = mListenerInfo;
6868            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
6869                    && li.mOnTouchListener.onTouch(this, event)) {
6870                return true;
6871            }
6872
6873            if (onTouchEvent(event)) {
6874                return true;
6875            }
6876        }
6877
6878        if (mInputEventConsistencyVerifier != null) {
6879            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6880        }
6881        return false;
6882    }
6883
6884    /**
6885     * Filter the touch event to apply security policies.
6886     *
6887     * @param event The motion event to be filtered.
6888     * @return True if the event should be dispatched, false if the event should be dropped.
6889     *
6890     * @see #getFilterTouchesWhenObscured
6891     */
6892    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
6893        //noinspection RedundantIfStatement
6894        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
6895                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
6896            // Window is obscured, drop this touch.
6897            return false;
6898        }
6899        return true;
6900    }
6901
6902    /**
6903     * Pass a trackball motion event down to the focused view.
6904     *
6905     * @param event The motion event to be dispatched.
6906     * @return True if the event was handled by the view, false otherwise.
6907     */
6908    public boolean dispatchTrackballEvent(MotionEvent event) {
6909        if (mInputEventConsistencyVerifier != null) {
6910            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
6911        }
6912
6913        return onTrackballEvent(event);
6914    }
6915
6916    /**
6917     * Dispatch a generic motion event.
6918     * <p>
6919     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6920     * are delivered to the view under the pointer.  All other generic motion events are
6921     * delivered to the focused view.  Hover events are handled specially and are delivered
6922     * to {@link #onHoverEvent(MotionEvent)}.
6923     * </p>
6924     *
6925     * @param event The motion event to be dispatched.
6926     * @return True if the event was handled by the view, false otherwise.
6927     */
6928    public boolean dispatchGenericMotionEvent(MotionEvent event) {
6929        if (mInputEventConsistencyVerifier != null) {
6930            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
6931        }
6932
6933        final int source = event.getSource();
6934        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
6935            final int action = event.getAction();
6936            if (action == MotionEvent.ACTION_HOVER_ENTER
6937                    || action == MotionEvent.ACTION_HOVER_MOVE
6938                    || action == MotionEvent.ACTION_HOVER_EXIT) {
6939                if (dispatchHoverEvent(event)) {
6940                    return true;
6941                }
6942            } else if (dispatchGenericPointerEvent(event)) {
6943                return true;
6944            }
6945        } else if (dispatchGenericFocusedEvent(event)) {
6946            return true;
6947        }
6948
6949        if (dispatchGenericMotionEventInternal(event)) {
6950            return true;
6951        }
6952
6953        if (mInputEventConsistencyVerifier != null) {
6954            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6955        }
6956        return false;
6957    }
6958
6959    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
6960        //noinspection SimplifiableIfStatement
6961        ListenerInfo li = mListenerInfo;
6962        if (li != null && li.mOnGenericMotionListener != null
6963                && (mViewFlags & ENABLED_MASK) == ENABLED
6964                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
6965            return true;
6966        }
6967
6968        if (onGenericMotionEvent(event)) {
6969            return true;
6970        }
6971
6972        if (mInputEventConsistencyVerifier != null) {
6973            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
6974        }
6975        return false;
6976    }
6977
6978    /**
6979     * Dispatch a hover event.
6980     * <p>
6981     * Do not call this method directly.
6982     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
6983     * </p>
6984     *
6985     * @param event The motion event to be dispatched.
6986     * @return True if the event was handled by the view, false otherwise.
6987     */
6988    protected boolean dispatchHoverEvent(MotionEvent event) {
6989        //noinspection SimplifiableIfStatement
6990        ListenerInfo li = mListenerInfo;
6991        if (li != null && li.mOnHoverListener != null
6992                && (mViewFlags & ENABLED_MASK) == ENABLED
6993                && li.mOnHoverListener.onHover(this, event)) {
6994            return true;
6995        }
6996
6997        return onHoverEvent(event);
6998    }
6999
7000    /**
7001     * Returns true if the view has a child to which it has recently sent
7002     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7003     * it does not have a hovered child, then it must be the innermost hovered view.
7004     * @hide
7005     */
7006    protected boolean hasHoveredChild() {
7007        return false;
7008    }
7009
7010    /**
7011     * Dispatch a generic motion event to the view under the first pointer.
7012     * <p>
7013     * Do not call this method directly.
7014     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7015     * </p>
7016     *
7017     * @param event The motion event to be dispatched.
7018     * @return True if the event was handled by the view, false otherwise.
7019     */
7020    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7021        return false;
7022    }
7023
7024    /**
7025     * Dispatch a generic motion event to the currently focused view.
7026     * <p>
7027     * Do not call this method directly.
7028     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7029     * </p>
7030     *
7031     * @param event The motion event to be dispatched.
7032     * @return True if the event was handled by the view, false otherwise.
7033     */
7034    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7035        return false;
7036    }
7037
7038    /**
7039     * Dispatch a pointer event.
7040     * <p>
7041     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7042     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7043     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7044     * and should not be expected to handle other pointing device features.
7045     * </p>
7046     *
7047     * @param event The motion event to be dispatched.
7048     * @return True if the event was handled by the view, false otherwise.
7049     * @hide
7050     */
7051    public final boolean dispatchPointerEvent(MotionEvent event) {
7052        if (event.isTouchEvent()) {
7053            return dispatchTouchEvent(event);
7054        } else {
7055            return dispatchGenericMotionEvent(event);
7056        }
7057    }
7058
7059    /**
7060     * Called when the window containing this view gains or loses window focus.
7061     * ViewGroups should override to route to their children.
7062     *
7063     * @param hasFocus True if the window containing this view now has focus,
7064     *        false otherwise.
7065     */
7066    public void dispatchWindowFocusChanged(boolean hasFocus) {
7067        onWindowFocusChanged(hasFocus);
7068    }
7069
7070    /**
7071     * Called when the window containing this view gains or loses focus.  Note
7072     * that this is separate from view focus: to receive key events, both
7073     * your view and its window must have focus.  If a window is displayed
7074     * on top of yours that takes input focus, then your own window will lose
7075     * focus but the view focus will remain unchanged.
7076     *
7077     * @param hasWindowFocus True if the window containing this view now has
7078     *        focus, false otherwise.
7079     */
7080    public void onWindowFocusChanged(boolean hasWindowFocus) {
7081        InputMethodManager imm = InputMethodManager.peekInstance();
7082        if (!hasWindowFocus) {
7083            if (isPressed()) {
7084                setPressed(false);
7085            }
7086            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7087                imm.focusOut(this);
7088            }
7089            removeLongPressCallback();
7090            removeTapCallback();
7091            onFocusLost();
7092        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
7093            imm.focusIn(this);
7094        }
7095        refreshDrawableState();
7096    }
7097
7098    /**
7099     * Returns true if this view is in a window that currently has window focus.
7100     * Note that this is not the same as the view itself having focus.
7101     *
7102     * @return True if this view is in a window that currently has window focus.
7103     */
7104    public boolean hasWindowFocus() {
7105        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7106    }
7107
7108    /**
7109     * Dispatch a view visibility change down the view hierarchy.
7110     * ViewGroups should override to route to their children.
7111     * @param changedView The view whose visibility changed. Could be 'this' or
7112     * an ancestor view.
7113     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7114     * {@link #INVISIBLE} or {@link #GONE}.
7115     */
7116    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7117        onVisibilityChanged(changedView, visibility);
7118    }
7119
7120    /**
7121     * Called when the visibility of the view or an ancestor of the view is changed.
7122     * @param changedView The view whose visibility changed. Could be 'this' or
7123     * an ancestor view.
7124     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7125     * {@link #INVISIBLE} or {@link #GONE}.
7126     */
7127    protected void onVisibilityChanged(View changedView, int visibility) {
7128        if (visibility == VISIBLE) {
7129            if (mAttachInfo != null) {
7130                initialAwakenScrollBars();
7131            } else {
7132                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
7133            }
7134        }
7135    }
7136
7137    /**
7138     * Dispatch a hint about whether this view is displayed. For instance, when
7139     * a View moves out of the screen, it might receives a display hint indicating
7140     * the view is not displayed. Applications should not <em>rely</em> on this hint
7141     * as there is no guarantee that they will receive one.
7142     *
7143     * @param hint A hint about whether or not this view is displayed:
7144     * {@link #VISIBLE} or {@link #INVISIBLE}.
7145     */
7146    public void dispatchDisplayHint(int hint) {
7147        onDisplayHint(hint);
7148    }
7149
7150    /**
7151     * Gives this view a hint about whether is displayed or not. For instance, when
7152     * a View moves out of the screen, it might receives a display hint indicating
7153     * the view is not displayed. Applications should not <em>rely</em> on this hint
7154     * as there is no guarantee that they will receive one.
7155     *
7156     * @param hint A hint about whether or not this view is displayed:
7157     * {@link #VISIBLE} or {@link #INVISIBLE}.
7158     */
7159    protected void onDisplayHint(int hint) {
7160    }
7161
7162    /**
7163     * Dispatch a window visibility change down the view hierarchy.
7164     * ViewGroups should override to route to their children.
7165     *
7166     * @param visibility The new visibility of the window.
7167     *
7168     * @see #onWindowVisibilityChanged(int)
7169     */
7170    public void dispatchWindowVisibilityChanged(int visibility) {
7171        onWindowVisibilityChanged(visibility);
7172    }
7173
7174    /**
7175     * Called when the window containing has change its visibility
7176     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7177     * that this tells you whether or not your window is being made visible
7178     * to the window manager; this does <em>not</em> tell you whether or not
7179     * your window is obscured by other windows on the screen, even if it
7180     * is itself visible.
7181     *
7182     * @param visibility The new visibility of the window.
7183     */
7184    protected void onWindowVisibilityChanged(int visibility) {
7185        if (visibility == VISIBLE) {
7186            initialAwakenScrollBars();
7187        }
7188    }
7189
7190    /**
7191     * Returns the current visibility of the window this view is attached to
7192     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7193     *
7194     * @return Returns the current visibility of the view's window.
7195     */
7196    public int getWindowVisibility() {
7197        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7198    }
7199
7200    /**
7201     * Retrieve the overall visible display size in which the window this view is
7202     * attached to has been positioned in.  This takes into account screen
7203     * decorations above the window, for both cases where the window itself
7204     * is being position inside of them or the window is being placed under
7205     * then and covered insets are used for the window to position its content
7206     * inside.  In effect, this tells you the available area where content can
7207     * be placed and remain visible to users.
7208     *
7209     * <p>This function requires an IPC back to the window manager to retrieve
7210     * the requested information, so should not be used in performance critical
7211     * code like drawing.
7212     *
7213     * @param outRect Filled in with the visible display frame.  If the view
7214     * is not attached to a window, this is simply the raw display size.
7215     */
7216    public void getWindowVisibleDisplayFrame(Rect outRect) {
7217        if (mAttachInfo != null) {
7218            try {
7219                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7220            } catch (RemoteException e) {
7221                return;
7222            }
7223            // XXX This is really broken, and probably all needs to be done
7224            // in the window manager, and we need to know more about whether
7225            // we want the area behind or in front of the IME.
7226            final Rect insets = mAttachInfo.mVisibleInsets;
7227            outRect.left += insets.left;
7228            outRect.top += insets.top;
7229            outRect.right -= insets.right;
7230            outRect.bottom -= insets.bottom;
7231            return;
7232        }
7233        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
7234        d.getRectSize(outRect);
7235    }
7236
7237    /**
7238     * Dispatch a notification about a resource configuration change down
7239     * the view hierarchy.
7240     * ViewGroups should override to route to their children.
7241     *
7242     * @param newConfig The new resource configuration.
7243     *
7244     * @see #onConfigurationChanged(android.content.res.Configuration)
7245     */
7246    public void dispatchConfigurationChanged(Configuration newConfig) {
7247        onConfigurationChanged(newConfig);
7248    }
7249
7250    /**
7251     * Called when the current configuration of the resources being used
7252     * by the application have changed.  You can use this to decide when
7253     * to reload resources that can changed based on orientation and other
7254     * configuration characterstics.  You only need to use this if you are
7255     * not relying on the normal {@link android.app.Activity} mechanism of
7256     * recreating the activity instance upon a configuration change.
7257     *
7258     * @param newConfig The new resource configuration.
7259     */
7260    protected void onConfigurationChanged(Configuration newConfig) {
7261    }
7262
7263    /**
7264     * Private function to aggregate all per-view attributes in to the view
7265     * root.
7266     */
7267    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7268        performCollectViewAttributes(attachInfo, visibility);
7269    }
7270
7271    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7272        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7273            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7274                attachInfo.mKeepScreenOn = true;
7275            }
7276            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7277            ListenerInfo li = mListenerInfo;
7278            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7279                attachInfo.mHasSystemUiListeners = true;
7280            }
7281        }
7282    }
7283
7284    void needGlobalAttributesUpdate(boolean force) {
7285        final AttachInfo ai = mAttachInfo;
7286        if (ai != null) {
7287            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7288                    || ai.mHasSystemUiListeners) {
7289                ai.mRecomputeGlobalAttributes = true;
7290            }
7291        }
7292    }
7293
7294    /**
7295     * Returns whether the device is currently in touch mode.  Touch mode is entered
7296     * once the user begins interacting with the device by touch, and affects various
7297     * things like whether focus is always visible to the user.
7298     *
7299     * @return Whether the device is in touch mode.
7300     */
7301    @ViewDebug.ExportedProperty
7302    public boolean isInTouchMode() {
7303        if (mAttachInfo != null) {
7304            return mAttachInfo.mInTouchMode;
7305        } else {
7306            return ViewRootImpl.isInTouchMode();
7307        }
7308    }
7309
7310    /**
7311     * Returns the context the view is running in, through which it can
7312     * access the current theme, resources, etc.
7313     *
7314     * @return The view's Context.
7315     */
7316    @ViewDebug.CapturedViewProperty
7317    public final Context getContext() {
7318        return mContext;
7319    }
7320
7321    /**
7322     * Handle a key event before it is processed by any input method
7323     * associated with the view hierarchy.  This can be used to intercept
7324     * key events in special situations before the IME consumes them; a
7325     * typical example would be handling the BACK key to update the application's
7326     * UI instead of allowing the IME to see it and close itself.
7327     *
7328     * @param keyCode The value in event.getKeyCode().
7329     * @param event Description of the key event.
7330     * @return If you handled the event, return true. If you want to allow the
7331     *         event to be handled by the next receiver, return false.
7332     */
7333    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7334        return false;
7335    }
7336
7337    /**
7338     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7339     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7340     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7341     * is released, if the view is enabled and clickable.
7342     *
7343     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7344     * although some may elect to do so in some situations. Do not rely on this to
7345     * catch software key presses.
7346     *
7347     * @param keyCode A key code that represents the button pressed, from
7348     *                {@link android.view.KeyEvent}.
7349     * @param event   The KeyEvent object that defines the button action.
7350     */
7351    public boolean onKeyDown(int keyCode, KeyEvent event) {
7352        boolean result = false;
7353
7354        switch (keyCode) {
7355            case KeyEvent.KEYCODE_DPAD_CENTER:
7356            case KeyEvent.KEYCODE_ENTER: {
7357                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7358                    return true;
7359                }
7360                // Long clickable items don't necessarily have to be clickable
7361                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7362                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7363                        (event.getRepeatCount() == 0)) {
7364                    setPressed(true);
7365                    checkForLongClick(0);
7366                    return true;
7367                }
7368                break;
7369            }
7370        }
7371        return result;
7372    }
7373
7374    /**
7375     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7376     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7377     * the event).
7378     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7379     * although some may elect to do so in some situations. Do not rely on this to
7380     * catch software key presses.
7381     */
7382    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7383        return false;
7384    }
7385
7386    /**
7387     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7388     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7389     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7390     * {@link KeyEvent#KEYCODE_ENTER} is released.
7391     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7392     * although some may elect to do so in some situations. Do not rely on this to
7393     * catch software key presses.
7394     *
7395     * @param keyCode A key code that represents the button pressed, from
7396     *                {@link android.view.KeyEvent}.
7397     * @param event   The KeyEvent object that defines the button action.
7398     */
7399    public boolean onKeyUp(int keyCode, KeyEvent event) {
7400        boolean result = false;
7401
7402        switch (keyCode) {
7403            case KeyEvent.KEYCODE_DPAD_CENTER:
7404            case KeyEvent.KEYCODE_ENTER: {
7405                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7406                    return true;
7407                }
7408                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7409                    setPressed(false);
7410
7411                    if (!mHasPerformedLongPress) {
7412                        // This is a tap, so remove the longpress check
7413                        removeLongPressCallback();
7414
7415                        result = performClick();
7416                    }
7417                }
7418                break;
7419            }
7420        }
7421        return result;
7422    }
7423
7424    /**
7425     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7426     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7427     * the event).
7428     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7429     * although some may elect to do so in some situations. Do not rely on this to
7430     * catch software key presses.
7431     *
7432     * @param keyCode     A key code that represents the button pressed, from
7433     *                    {@link android.view.KeyEvent}.
7434     * @param repeatCount The number of times the action was made.
7435     * @param event       The KeyEvent object that defines the button action.
7436     */
7437    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7438        return false;
7439    }
7440
7441    /**
7442     * Called on the focused view when a key shortcut event is not handled.
7443     * Override this method to implement local key shortcuts for the View.
7444     * Key shortcuts can also be implemented by setting the
7445     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7446     *
7447     * @param keyCode The value in event.getKeyCode().
7448     * @param event Description of the key event.
7449     * @return If you handled the event, return true. If you want to allow the
7450     *         event to be handled by the next receiver, return false.
7451     */
7452    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7453        return false;
7454    }
7455
7456    /**
7457     * Check whether the called view is a text editor, in which case it
7458     * would make sense to automatically display a soft input window for
7459     * it.  Subclasses should override this if they implement
7460     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7461     * a call on that method would return a non-null InputConnection, and
7462     * they are really a first-class editor that the user would normally
7463     * start typing on when the go into a window containing your view.
7464     *
7465     * <p>The default implementation always returns false.  This does
7466     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7467     * will not be called or the user can not otherwise perform edits on your
7468     * view; it is just a hint to the system that this is not the primary
7469     * purpose of this view.
7470     *
7471     * @return Returns true if this view is a text editor, else false.
7472     */
7473    public boolean onCheckIsTextEditor() {
7474        return false;
7475    }
7476
7477    /**
7478     * Create a new InputConnection for an InputMethod to interact
7479     * with the view.  The default implementation returns null, since it doesn't
7480     * support input methods.  You can override this to implement such support.
7481     * This is only needed for views that take focus and text input.
7482     *
7483     * <p>When implementing this, you probably also want to implement
7484     * {@link #onCheckIsTextEditor()} to indicate you will return a
7485     * non-null InputConnection.
7486     *
7487     * @param outAttrs Fill in with attribute information about the connection.
7488     */
7489    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
7490        return null;
7491    }
7492
7493    /**
7494     * Called by the {@link android.view.inputmethod.InputMethodManager}
7495     * when a view who is not the current
7496     * input connection target is trying to make a call on the manager.  The
7497     * default implementation returns false; you can override this to return
7498     * true for certain views if you are performing InputConnection proxying
7499     * to them.
7500     * @param view The View that is making the InputMethodManager call.
7501     * @return Return true to allow the call, false to reject.
7502     */
7503    public boolean checkInputConnectionProxy(View view) {
7504        return false;
7505    }
7506
7507    /**
7508     * Show the context menu for this view. It is not safe to hold on to the
7509     * menu after returning from this method.
7510     *
7511     * You should normally not overload this method. Overload
7512     * {@link #onCreateContextMenu(ContextMenu)} or define an
7513     * {@link OnCreateContextMenuListener} to add items to the context menu.
7514     *
7515     * @param menu The context menu to populate
7516     */
7517    public void createContextMenu(ContextMenu menu) {
7518        ContextMenuInfo menuInfo = getContextMenuInfo();
7519
7520        // Sets the current menu info so all items added to menu will have
7521        // my extra info set.
7522        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
7523
7524        onCreateContextMenu(menu);
7525        ListenerInfo li = mListenerInfo;
7526        if (li != null && li.mOnCreateContextMenuListener != null) {
7527            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
7528        }
7529
7530        // Clear the extra information so subsequent items that aren't mine don't
7531        // have my extra info.
7532        ((MenuBuilder)menu).setCurrentMenuInfo(null);
7533
7534        if (mParent != null) {
7535            mParent.createContextMenu(menu);
7536        }
7537    }
7538
7539    /**
7540     * Views should implement this if they have extra information to associate
7541     * with the context menu. The return result is supplied as a parameter to
7542     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
7543     * callback.
7544     *
7545     * @return Extra information about the item for which the context menu
7546     *         should be shown. This information will vary across different
7547     *         subclasses of View.
7548     */
7549    protected ContextMenuInfo getContextMenuInfo() {
7550        return null;
7551    }
7552
7553    /**
7554     * Views should implement this if the view itself is going to add items to
7555     * the context menu.
7556     *
7557     * @param menu the context menu to populate
7558     */
7559    protected void onCreateContextMenu(ContextMenu menu) {
7560    }
7561
7562    /**
7563     * Implement this method to handle trackball motion events.  The
7564     * <em>relative</em> movement of the trackball since the last event
7565     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
7566     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
7567     * that a movement of 1 corresponds to the user pressing one DPAD key (so
7568     * they will often be fractional values, representing the more fine-grained
7569     * movement information available from a trackball).
7570     *
7571     * @param event The motion event.
7572     * @return True if the event was handled, false otherwise.
7573     */
7574    public boolean onTrackballEvent(MotionEvent event) {
7575        return false;
7576    }
7577
7578    /**
7579     * Implement this method to handle generic motion events.
7580     * <p>
7581     * Generic motion events describe joystick movements, mouse hovers, track pad
7582     * touches, scroll wheel movements and other input events.  The
7583     * {@link MotionEvent#getSource() source} of the motion event specifies
7584     * the class of input that was received.  Implementations of this method
7585     * must examine the bits in the source before processing the event.
7586     * The following code example shows how this is done.
7587     * </p><p>
7588     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7589     * are delivered to the view under the pointer.  All other generic motion events are
7590     * delivered to the focused view.
7591     * </p>
7592     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
7593     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
7594     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
7595     *             // process the joystick movement...
7596     *             return true;
7597     *         }
7598     *     }
7599     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
7600     *         switch (event.getAction()) {
7601     *             case MotionEvent.ACTION_HOVER_MOVE:
7602     *                 // process the mouse hover movement...
7603     *                 return true;
7604     *             case MotionEvent.ACTION_SCROLL:
7605     *                 // process the scroll wheel movement...
7606     *                 return true;
7607     *         }
7608     *     }
7609     *     return super.onGenericMotionEvent(event);
7610     * }</pre>
7611     *
7612     * @param event The generic motion event being processed.
7613     * @return True if the event was handled, false otherwise.
7614     */
7615    public boolean onGenericMotionEvent(MotionEvent event) {
7616        return false;
7617    }
7618
7619    /**
7620     * Implement this method to handle hover events.
7621     * <p>
7622     * This method is called whenever a pointer is hovering into, over, or out of the
7623     * bounds of a view and the view is not currently being touched.
7624     * Hover events are represented as pointer events with action
7625     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
7626     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
7627     * </p>
7628     * <ul>
7629     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
7630     * when the pointer enters the bounds of the view.</li>
7631     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
7632     * when the pointer has already entered the bounds of the view and has moved.</li>
7633     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
7634     * when the pointer has exited the bounds of the view or when the pointer is
7635     * about to go down due to a button click, tap, or similar user action that
7636     * causes the view to be touched.</li>
7637     * </ul>
7638     * <p>
7639     * The view should implement this method to return true to indicate that it is
7640     * handling the hover event, such as by changing its drawable state.
7641     * </p><p>
7642     * The default implementation calls {@link #setHovered} to update the hovered state
7643     * of the view when a hover enter or hover exit event is received, if the view
7644     * is enabled and is clickable.  The default implementation also sends hover
7645     * accessibility events.
7646     * </p>
7647     *
7648     * @param event The motion event that describes the hover.
7649     * @return True if the view handled the hover event.
7650     *
7651     * @see #isHovered
7652     * @see #setHovered
7653     * @see #onHoverChanged
7654     */
7655    public boolean onHoverEvent(MotionEvent event) {
7656        // The root view may receive hover (or touch) events that are outside the bounds of
7657        // the window.  This code ensures that we only send accessibility events for
7658        // hovers that are actually within the bounds of the root view.
7659        final int action = event.getActionMasked();
7660        if (!mSendingHoverAccessibilityEvents) {
7661            if ((action == MotionEvent.ACTION_HOVER_ENTER
7662                    || action == MotionEvent.ACTION_HOVER_MOVE)
7663                    && !hasHoveredChild()
7664                    && pointInView(event.getX(), event.getY())) {
7665                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
7666                mSendingHoverAccessibilityEvents = true;
7667            }
7668        } else {
7669            if (action == MotionEvent.ACTION_HOVER_EXIT
7670                    || (action == MotionEvent.ACTION_MOVE
7671                            && !pointInView(event.getX(), event.getY()))) {
7672                mSendingHoverAccessibilityEvents = false;
7673                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
7674                // If the window does not have input focus we take away accessibility
7675                // focus as soon as the user stop hovering over the view.
7676                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
7677                    getViewRootImpl().setAccessibilityFocus(null, null);
7678                }
7679            }
7680        }
7681
7682        if (isHoverable()) {
7683            switch (action) {
7684                case MotionEvent.ACTION_HOVER_ENTER:
7685                    setHovered(true);
7686                    break;
7687                case MotionEvent.ACTION_HOVER_EXIT:
7688                    setHovered(false);
7689                    break;
7690            }
7691
7692            // Dispatch the event to onGenericMotionEvent before returning true.
7693            // This is to provide compatibility with existing applications that
7694            // handled HOVER_MOVE events in onGenericMotionEvent and that would
7695            // break because of the new default handling for hoverable views
7696            // in onHoverEvent.
7697            // Note that onGenericMotionEvent will be called by default when
7698            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
7699            dispatchGenericMotionEventInternal(event);
7700            return true;
7701        }
7702
7703        return false;
7704    }
7705
7706    /**
7707     * Returns true if the view should handle {@link #onHoverEvent}
7708     * by calling {@link #setHovered} to change its hovered state.
7709     *
7710     * @return True if the view is hoverable.
7711     */
7712    private boolean isHoverable() {
7713        final int viewFlags = mViewFlags;
7714        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7715            return false;
7716        }
7717
7718        return (viewFlags & CLICKABLE) == CLICKABLE
7719                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
7720    }
7721
7722    /**
7723     * Returns true if the view is currently hovered.
7724     *
7725     * @return True if the view is currently hovered.
7726     *
7727     * @see #setHovered
7728     * @see #onHoverChanged
7729     */
7730    @ViewDebug.ExportedProperty
7731    public boolean isHovered() {
7732        return (mPrivateFlags & HOVERED) != 0;
7733    }
7734
7735    /**
7736     * Sets whether the view is currently hovered.
7737     * <p>
7738     * Calling this method also changes the drawable state of the view.  This
7739     * enables the view to react to hover by using different drawable resources
7740     * to change its appearance.
7741     * </p><p>
7742     * The {@link #onHoverChanged} method is called when the hovered state changes.
7743     * </p>
7744     *
7745     * @param hovered True if the view is hovered.
7746     *
7747     * @see #isHovered
7748     * @see #onHoverChanged
7749     */
7750    public void setHovered(boolean hovered) {
7751        if (hovered) {
7752            if ((mPrivateFlags & HOVERED) == 0) {
7753                mPrivateFlags |= HOVERED;
7754                refreshDrawableState();
7755                onHoverChanged(true);
7756            }
7757        } else {
7758            if ((mPrivateFlags & HOVERED) != 0) {
7759                mPrivateFlags &= ~HOVERED;
7760                refreshDrawableState();
7761                onHoverChanged(false);
7762            }
7763        }
7764    }
7765
7766    /**
7767     * Implement this method to handle hover state changes.
7768     * <p>
7769     * This method is called whenever the hover state changes as a result of a
7770     * call to {@link #setHovered}.
7771     * </p>
7772     *
7773     * @param hovered The current hover state, as returned by {@link #isHovered}.
7774     *
7775     * @see #isHovered
7776     * @see #setHovered
7777     */
7778    public void onHoverChanged(boolean hovered) {
7779    }
7780
7781    /**
7782     * Implement this method to handle touch screen motion events.
7783     *
7784     * @param event The motion event.
7785     * @return True if the event was handled, false otherwise.
7786     */
7787    public boolean onTouchEvent(MotionEvent event) {
7788        final int viewFlags = mViewFlags;
7789
7790        if ((viewFlags & ENABLED_MASK) == DISABLED) {
7791            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
7792                setPressed(false);
7793            }
7794            // A disabled view that is clickable still consumes the touch
7795            // events, it just doesn't respond to them.
7796            return (((viewFlags & CLICKABLE) == CLICKABLE ||
7797                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
7798        }
7799
7800        if (mTouchDelegate != null) {
7801            if (mTouchDelegate.onTouchEvent(event)) {
7802                return true;
7803            }
7804        }
7805
7806        if (((viewFlags & CLICKABLE) == CLICKABLE ||
7807                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
7808            switch (event.getAction()) {
7809                case MotionEvent.ACTION_UP:
7810                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
7811                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
7812                        // take focus if we don't have it already and we should in
7813                        // touch mode.
7814                        boolean focusTaken = false;
7815                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
7816                            focusTaken = requestFocus();
7817                        }
7818
7819                        if (prepressed) {
7820                            // The button is being released before we actually
7821                            // showed it as pressed.  Make it show the pressed
7822                            // state now (before scheduling the click) to ensure
7823                            // the user sees it.
7824                            setPressed(true);
7825                       }
7826
7827                        if (!mHasPerformedLongPress) {
7828                            // This is a tap, so remove the longpress check
7829                            removeLongPressCallback();
7830
7831                            // Only perform take click actions if we were in the pressed state
7832                            if (!focusTaken) {
7833                                // Use a Runnable and post this rather than calling
7834                                // performClick directly. This lets other visual state
7835                                // of the view update before click actions start.
7836                                if (mPerformClick == null) {
7837                                    mPerformClick = new PerformClick();
7838                                }
7839                                if (!post(mPerformClick)) {
7840                                    performClick();
7841                                }
7842                            }
7843                        }
7844
7845                        if (mUnsetPressedState == null) {
7846                            mUnsetPressedState = new UnsetPressedState();
7847                        }
7848
7849                        if (prepressed) {
7850                            postDelayed(mUnsetPressedState,
7851                                    ViewConfiguration.getPressedStateDuration());
7852                        } else if (!post(mUnsetPressedState)) {
7853                            // If the post failed, unpress right now
7854                            mUnsetPressedState.run();
7855                        }
7856                        removeTapCallback();
7857                    }
7858                    break;
7859
7860                case MotionEvent.ACTION_DOWN:
7861                    mHasPerformedLongPress = false;
7862
7863                    if (performButtonActionOnTouchDown(event)) {
7864                        break;
7865                    }
7866
7867                    // Walk up the hierarchy to determine if we're inside a scrolling container.
7868                    boolean isInScrollingContainer = isInScrollingContainer();
7869
7870                    // For views inside a scrolling container, delay the pressed feedback for
7871                    // a short period in case this is a scroll.
7872                    if (isInScrollingContainer) {
7873                        mPrivateFlags |= PREPRESSED;
7874                        if (mPendingCheckForTap == null) {
7875                            mPendingCheckForTap = new CheckForTap();
7876                        }
7877                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
7878                    } else {
7879                        // Not inside a scrolling container, so show the feedback right away
7880                        setPressed(true);
7881                        checkForLongClick(0);
7882                    }
7883                    break;
7884
7885                case MotionEvent.ACTION_CANCEL:
7886                    setPressed(false);
7887                    removeTapCallback();
7888                    break;
7889
7890                case MotionEvent.ACTION_MOVE:
7891                    final int x = (int) event.getX();
7892                    final int y = (int) event.getY();
7893
7894                    // Be lenient about moving outside of buttons
7895                    if (!pointInView(x, y, mTouchSlop)) {
7896                        // Outside button
7897                        removeTapCallback();
7898                        if ((mPrivateFlags & PRESSED) != 0) {
7899                            // Remove any future long press/tap checks
7900                            removeLongPressCallback();
7901
7902                            setPressed(false);
7903                        }
7904                    }
7905                    break;
7906            }
7907            return true;
7908        }
7909
7910        return false;
7911    }
7912
7913    /**
7914     * @hide
7915     */
7916    public boolean isInScrollingContainer() {
7917        ViewParent p = getParent();
7918        while (p != null && p instanceof ViewGroup) {
7919            if (((ViewGroup) p).shouldDelayChildPressedState()) {
7920                return true;
7921            }
7922            p = p.getParent();
7923        }
7924        return false;
7925    }
7926
7927    /**
7928     * Remove the longpress detection timer.
7929     */
7930    private void removeLongPressCallback() {
7931        if (mPendingCheckForLongPress != null) {
7932          removeCallbacks(mPendingCheckForLongPress);
7933        }
7934    }
7935
7936    /**
7937     * Remove the pending click action
7938     */
7939    private void removePerformClickCallback() {
7940        if (mPerformClick != null) {
7941            removeCallbacks(mPerformClick);
7942        }
7943    }
7944
7945    /**
7946     * Remove the prepress detection timer.
7947     */
7948    private void removeUnsetPressCallback() {
7949        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
7950            setPressed(false);
7951            removeCallbacks(mUnsetPressedState);
7952        }
7953    }
7954
7955    /**
7956     * Remove the tap detection timer.
7957     */
7958    private void removeTapCallback() {
7959        if (mPendingCheckForTap != null) {
7960            mPrivateFlags &= ~PREPRESSED;
7961            removeCallbacks(mPendingCheckForTap);
7962        }
7963    }
7964
7965    /**
7966     * Cancels a pending long press.  Your subclass can use this if you
7967     * want the context menu to come up if the user presses and holds
7968     * at the same place, but you don't want it to come up if they press
7969     * and then move around enough to cause scrolling.
7970     */
7971    public void cancelLongPress() {
7972        removeLongPressCallback();
7973
7974        /*
7975         * The prepressed state handled by the tap callback is a display
7976         * construct, but the tap callback will post a long press callback
7977         * less its own timeout. Remove it here.
7978         */
7979        removeTapCallback();
7980    }
7981
7982    /**
7983     * Remove the pending callback for sending a
7984     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
7985     */
7986    private void removeSendViewScrolledAccessibilityEventCallback() {
7987        if (mSendViewScrolledAccessibilityEvent != null) {
7988            removeCallbacks(mSendViewScrolledAccessibilityEvent);
7989            mSendViewScrolledAccessibilityEvent.mIsPending = false;
7990        }
7991    }
7992
7993    /**
7994     * Sets the TouchDelegate for this View.
7995     */
7996    public void setTouchDelegate(TouchDelegate delegate) {
7997        mTouchDelegate = delegate;
7998    }
7999
8000    /**
8001     * Gets the TouchDelegate for this View.
8002     */
8003    public TouchDelegate getTouchDelegate() {
8004        return mTouchDelegate;
8005    }
8006
8007    /**
8008     * Set flags controlling behavior of this view.
8009     *
8010     * @param flags Constant indicating the value which should be set
8011     * @param mask Constant indicating the bit range that should be changed
8012     */
8013    void setFlags(int flags, int mask) {
8014        int old = mViewFlags;
8015        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8016
8017        int changed = mViewFlags ^ old;
8018        if (changed == 0) {
8019            return;
8020        }
8021        int privateFlags = mPrivateFlags;
8022
8023        /* Check if the FOCUSABLE bit has changed */
8024        if (((changed & FOCUSABLE_MASK) != 0) &&
8025                ((privateFlags & HAS_BOUNDS) !=0)) {
8026            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8027                    && ((privateFlags & FOCUSED) != 0)) {
8028                /* Give up focus if we are no longer focusable */
8029                clearFocus();
8030            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8031                    && ((privateFlags & FOCUSED) == 0)) {
8032                /*
8033                 * Tell the view system that we are now available to take focus
8034                 * if no one else already has it.
8035                 */
8036                if (mParent != null) mParent.focusableViewAvailable(this);
8037            }
8038            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8039                notifyAccessibilityStateChanged();
8040            }
8041        }
8042
8043        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8044            if ((changed & VISIBILITY_MASK) != 0) {
8045                /*
8046                 * If this view is becoming visible, invalidate it in case it changed while
8047                 * it was not visible. Marking it drawn ensures that the invalidation will
8048                 * go through.
8049                 */
8050                mPrivateFlags |= DRAWN;
8051                invalidate(true);
8052
8053                needGlobalAttributesUpdate(true);
8054
8055                // a view becoming visible is worth notifying the parent
8056                // about in case nothing has focus.  even if this specific view
8057                // isn't focusable, it may contain something that is, so let
8058                // the root view try to give this focus if nothing else does.
8059                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8060                    mParent.focusableViewAvailable(this);
8061                }
8062            }
8063        }
8064
8065        /* Check if the GONE bit has changed */
8066        if ((changed & GONE) != 0) {
8067            needGlobalAttributesUpdate(false);
8068            requestLayout();
8069
8070            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8071                if (hasFocus()) clearFocus();
8072                clearAccessibilityFocus();
8073                destroyDrawingCache();
8074                if (mParent instanceof View) {
8075                    // GONE views noop invalidation, so invalidate the parent
8076                    ((View) mParent).invalidate(true);
8077                }
8078                // Mark the view drawn to ensure that it gets invalidated properly the next
8079                // time it is visible and gets invalidated
8080                mPrivateFlags |= DRAWN;
8081            }
8082            if (mAttachInfo != null) {
8083                mAttachInfo.mViewVisibilityChanged = true;
8084            }
8085        }
8086
8087        /* Check if the VISIBLE bit has changed */
8088        if ((changed & INVISIBLE) != 0) {
8089            needGlobalAttributesUpdate(false);
8090            /*
8091             * If this view is becoming invisible, set the DRAWN flag so that
8092             * the next invalidate() will not be skipped.
8093             */
8094            mPrivateFlags |= DRAWN;
8095
8096            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8097                // root view becoming invisible shouldn't clear focus and accessibility focus
8098                if (getRootView() != this) {
8099                    clearFocus();
8100                    clearAccessibilityFocus();
8101                }
8102            }
8103            if (mAttachInfo != null) {
8104                mAttachInfo.mViewVisibilityChanged = true;
8105            }
8106        }
8107
8108        if ((changed & VISIBILITY_MASK) != 0) {
8109            if (mParent instanceof ViewGroup) {
8110                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8111                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8112                ((View) mParent).invalidate(true);
8113            } else if (mParent != null) {
8114                mParent.invalidateChild(this, null);
8115            }
8116            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8117        }
8118
8119        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8120            destroyDrawingCache();
8121        }
8122
8123        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8124            destroyDrawingCache();
8125            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8126            invalidateParentCaches();
8127        }
8128
8129        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8130            destroyDrawingCache();
8131            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8132        }
8133
8134        if ((changed & DRAW_MASK) != 0) {
8135            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8136                if (mBackground != null) {
8137                    mPrivateFlags &= ~SKIP_DRAW;
8138                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
8139                } else {
8140                    mPrivateFlags |= SKIP_DRAW;
8141                }
8142            } else {
8143                mPrivateFlags &= ~SKIP_DRAW;
8144            }
8145            requestLayout();
8146            invalidate(true);
8147        }
8148
8149        if ((changed & KEEP_SCREEN_ON) != 0) {
8150            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8151                mParent.recomputeViewAttributes(this);
8152            }
8153        }
8154
8155        if (AccessibilityManager.getInstance(mContext).isEnabled()
8156                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8157                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8158            notifyAccessibilityStateChanged();
8159        }
8160    }
8161
8162    /**
8163     * Change the view's z order in the tree, so it's on top of other sibling
8164     * views
8165     */
8166    public void bringToFront() {
8167        if (mParent != null) {
8168            mParent.bringChildToFront(this);
8169        }
8170    }
8171
8172    /**
8173     * This is called in response to an internal scroll in this view (i.e., the
8174     * view scrolled its own contents). This is typically as a result of
8175     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8176     * called.
8177     *
8178     * @param l Current horizontal scroll origin.
8179     * @param t Current vertical scroll origin.
8180     * @param oldl Previous horizontal scroll origin.
8181     * @param oldt Previous vertical scroll origin.
8182     */
8183    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8184        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8185            postSendViewScrolledAccessibilityEventCallback();
8186        }
8187
8188        mBackgroundSizeChanged = true;
8189
8190        final AttachInfo ai = mAttachInfo;
8191        if (ai != null) {
8192            ai.mViewScrollChanged = true;
8193        }
8194    }
8195
8196    /**
8197     * Interface definition for a callback to be invoked when the layout bounds of a view
8198     * changes due to layout processing.
8199     */
8200    public interface OnLayoutChangeListener {
8201        /**
8202         * Called when the focus state of a view has changed.
8203         *
8204         * @param v The view whose state has changed.
8205         * @param left The new value of the view's left property.
8206         * @param top The new value of the view's top property.
8207         * @param right The new value of the view's right property.
8208         * @param bottom The new value of the view's bottom property.
8209         * @param oldLeft The previous value of the view's left property.
8210         * @param oldTop The previous value of the view's top property.
8211         * @param oldRight The previous value of the view's right property.
8212         * @param oldBottom The previous value of the view's bottom property.
8213         */
8214        void onLayoutChange(View v, int left, int top, int right, int bottom,
8215            int oldLeft, int oldTop, int oldRight, int oldBottom);
8216    }
8217
8218    /**
8219     * This is called during layout when the size of this view has changed. If
8220     * you were just added to the view hierarchy, you're called with the old
8221     * values of 0.
8222     *
8223     * @param w Current width of this view.
8224     * @param h Current height of this view.
8225     * @param oldw Old width of this view.
8226     * @param oldh Old height of this view.
8227     */
8228    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8229    }
8230
8231    /**
8232     * Called by draw to draw the child views. This may be overridden
8233     * by derived classes to gain control just before its children are drawn
8234     * (but after its own view has been drawn).
8235     * @param canvas the canvas on which to draw the view
8236     */
8237    protected void dispatchDraw(Canvas canvas) {
8238
8239    }
8240
8241    /**
8242     * Gets the parent of this view. Note that the parent is a
8243     * ViewParent and not necessarily a View.
8244     *
8245     * @return Parent of this view.
8246     */
8247    public final ViewParent getParent() {
8248        return mParent;
8249    }
8250
8251    /**
8252     * Set the horizontal scrolled position of your view. This will cause a call to
8253     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8254     * invalidated.
8255     * @param value the x position to scroll to
8256     */
8257    public void setScrollX(int value) {
8258        scrollTo(value, mScrollY);
8259    }
8260
8261    /**
8262     * Set the vertical scrolled position of your view. This will cause a call to
8263     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8264     * invalidated.
8265     * @param value the y position to scroll to
8266     */
8267    public void setScrollY(int value) {
8268        scrollTo(mScrollX, value);
8269    }
8270
8271    /**
8272     * Return the scrolled left position of this view. This is the left edge of
8273     * the displayed part of your view. You do not need to draw any pixels
8274     * farther left, since those are outside of the frame of your view on
8275     * screen.
8276     *
8277     * @return The left edge of the displayed part of your view, in pixels.
8278     */
8279    public final int getScrollX() {
8280        return mScrollX;
8281    }
8282
8283    /**
8284     * Return the scrolled top position of this view. This is the top edge of
8285     * the displayed part of your view. You do not need to draw any pixels above
8286     * it, since those are outside of the frame of your view on screen.
8287     *
8288     * @return The top edge of the displayed part of your view, in pixels.
8289     */
8290    public final int getScrollY() {
8291        return mScrollY;
8292    }
8293
8294    /**
8295     * Return the width of the your view.
8296     *
8297     * @return The width of your view, in pixels.
8298     */
8299    @ViewDebug.ExportedProperty(category = "layout")
8300    public final int getWidth() {
8301        return mRight - mLeft;
8302    }
8303
8304    /**
8305     * Return the height of your view.
8306     *
8307     * @return The height of your view, in pixels.
8308     */
8309    @ViewDebug.ExportedProperty(category = "layout")
8310    public final int getHeight() {
8311        return mBottom - mTop;
8312    }
8313
8314    /**
8315     * Return the visible drawing bounds of your view. Fills in the output
8316     * rectangle with the values from getScrollX(), getScrollY(),
8317     * getWidth(), and getHeight().
8318     *
8319     * @param outRect The (scrolled) drawing bounds of the view.
8320     */
8321    public void getDrawingRect(Rect outRect) {
8322        outRect.left = mScrollX;
8323        outRect.top = mScrollY;
8324        outRect.right = mScrollX + (mRight - mLeft);
8325        outRect.bottom = mScrollY + (mBottom - mTop);
8326    }
8327
8328    /**
8329     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8330     * raw width component (that is the result is masked by
8331     * {@link #MEASURED_SIZE_MASK}).
8332     *
8333     * @return The raw measured width of this view.
8334     */
8335    public final int getMeasuredWidth() {
8336        return mMeasuredWidth & MEASURED_SIZE_MASK;
8337    }
8338
8339    /**
8340     * Return the full width measurement information for this view as computed
8341     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8342     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8343     * This should be used during measurement and layout calculations only. Use
8344     * {@link #getWidth()} to see how wide a view is after layout.
8345     *
8346     * @return The measured width of this view as a bit mask.
8347     */
8348    public final int getMeasuredWidthAndState() {
8349        return mMeasuredWidth;
8350    }
8351
8352    /**
8353     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8354     * raw width component (that is the result is masked by
8355     * {@link #MEASURED_SIZE_MASK}).
8356     *
8357     * @return The raw measured height of this view.
8358     */
8359    public final int getMeasuredHeight() {
8360        return mMeasuredHeight & MEASURED_SIZE_MASK;
8361    }
8362
8363    /**
8364     * Return the full height measurement information for this view as computed
8365     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8366     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8367     * This should be used during measurement and layout calculations only. Use
8368     * {@link #getHeight()} to see how wide a view is after layout.
8369     *
8370     * @return The measured width of this view as a bit mask.
8371     */
8372    public final int getMeasuredHeightAndState() {
8373        return mMeasuredHeight;
8374    }
8375
8376    /**
8377     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8378     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8379     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8380     * and the height component is at the shifted bits
8381     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8382     */
8383    public final int getMeasuredState() {
8384        return (mMeasuredWidth&MEASURED_STATE_MASK)
8385                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8386                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8387    }
8388
8389    /**
8390     * The transform matrix of this view, which is calculated based on the current
8391     * roation, scale, and pivot properties.
8392     *
8393     * @see #getRotation()
8394     * @see #getScaleX()
8395     * @see #getScaleY()
8396     * @see #getPivotX()
8397     * @see #getPivotY()
8398     * @return The current transform matrix for the view
8399     */
8400    public Matrix getMatrix() {
8401        if (mTransformationInfo != null) {
8402            updateMatrix();
8403            return mTransformationInfo.mMatrix;
8404        }
8405        return Matrix.IDENTITY_MATRIX;
8406    }
8407
8408    /**
8409     * Utility function to determine if the value is far enough away from zero to be
8410     * considered non-zero.
8411     * @param value A floating point value to check for zero-ness
8412     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8413     */
8414    private static boolean nonzero(float value) {
8415        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8416    }
8417
8418    /**
8419     * Returns true if the transform matrix is the identity matrix.
8420     * Recomputes the matrix if necessary.
8421     *
8422     * @return True if the transform matrix is the identity matrix, false otherwise.
8423     */
8424    final boolean hasIdentityMatrix() {
8425        if (mTransformationInfo != null) {
8426            updateMatrix();
8427            return mTransformationInfo.mMatrixIsIdentity;
8428        }
8429        return true;
8430    }
8431
8432    void ensureTransformationInfo() {
8433        if (mTransformationInfo == null) {
8434            mTransformationInfo = new TransformationInfo();
8435        }
8436    }
8437
8438    /**
8439     * Recomputes the transform matrix if necessary.
8440     */
8441    private void updateMatrix() {
8442        final TransformationInfo info = mTransformationInfo;
8443        if (info == null) {
8444            return;
8445        }
8446        if (info.mMatrixDirty) {
8447            // transform-related properties have changed since the last time someone
8448            // asked for the matrix; recalculate it with the current values
8449
8450            // Figure out if we need to update the pivot point
8451            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8452                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8453                    info.mPrevWidth = mRight - mLeft;
8454                    info.mPrevHeight = mBottom - mTop;
8455                    info.mPivotX = info.mPrevWidth / 2f;
8456                    info.mPivotY = info.mPrevHeight / 2f;
8457                }
8458            }
8459            info.mMatrix.reset();
8460            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8461                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8462                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8463                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8464            } else {
8465                if (info.mCamera == null) {
8466                    info.mCamera = new Camera();
8467                    info.matrix3D = new Matrix();
8468                }
8469                info.mCamera.save();
8470                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8471                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8472                info.mCamera.getMatrix(info.matrix3D);
8473                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8474                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8475                        info.mPivotY + info.mTranslationY);
8476                info.mMatrix.postConcat(info.matrix3D);
8477                info.mCamera.restore();
8478            }
8479            info.mMatrixDirty = false;
8480            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
8481            info.mInverseMatrixDirty = true;
8482        }
8483    }
8484
8485    /**
8486     * When searching for a view to focus this rectangle is used when considering if this view is
8487     * a good candidate for receiving focus.
8488     *
8489     * By default, the rectangle is the {@link #getDrawingRect}) of the view.
8490     *
8491     * @param r The rectangle to fill in, in this view's coordinates.
8492     */
8493    public void getFocusRect(Rect r) {
8494        getDrawingRect(r);
8495    }
8496
8497   /**
8498     * Utility method to retrieve the inverse of the current mMatrix property.
8499     * We cache the matrix to avoid recalculating it when transform properties
8500     * have not changed.
8501     *
8502     * @return The inverse of the current matrix of this view.
8503     */
8504    final Matrix getInverseMatrix() {
8505        final TransformationInfo info = mTransformationInfo;
8506        if (info != null) {
8507            updateMatrix();
8508            if (info.mInverseMatrixDirty) {
8509                if (info.mInverseMatrix == null) {
8510                    info.mInverseMatrix = new Matrix();
8511                }
8512                info.mMatrix.invert(info.mInverseMatrix);
8513                info.mInverseMatrixDirty = false;
8514            }
8515            return info.mInverseMatrix;
8516        }
8517        return Matrix.IDENTITY_MATRIX;
8518    }
8519
8520    /**
8521     * Gets the distance along the Z axis from the camera to this view.
8522     *
8523     * @see #setCameraDistance(float)
8524     *
8525     * @return The distance along the Z axis.
8526     */
8527    public float getCameraDistance() {
8528        ensureTransformationInfo();
8529        final float dpi = mResources.getDisplayMetrics().densityDpi;
8530        final TransformationInfo info = mTransformationInfo;
8531        if (info.mCamera == null) {
8532            info.mCamera = new Camera();
8533            info.matrix3D = new Matrix();
8534        }
8535        return -(info.mCamera.getLocationZ() * dpi);
8536    }
8537
8538    /**
8539     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
8540     * views are drawn) from the camera to this view. The camera's distance
8541     * affects 3D transformations, for instance rotations around the X and Y
8542     * axis. If the rotationX or rotationY properties are changed and this view is
8543     * large (more than half the size of the screen), it is recommended to always
8544     * use a camera distance that's greater than the height (X axis rotation) or
8545     * the width (Y axis rotation) of this view.</p>
8546     *
8547     * <p>The distance of the camera from the view plane can have an affect on the
8548     * perspective distortion of the view when it is rotated around the x or y axis.
8549     * For example, a large distance will result in a large viewing angle, and there
8550     * will not be much perspective distortion of the view as it rotates. A short
8551     * distance may cause much more perspective distortion upon rotation, and can
8552     * also result in some drawing artifacts if the rotated view ends up partially
8553     * behind the camera (which is why the recommendation is to use a distance at
8554     * least as far as the size of the view, if the view is to be rotated.)</p>
8555     *
8556     * <p>The distance is expressed in "depth pixels." The default distance depends
8557     * on the screen density. For instance, on a medium density display, the
8558     * default distance is 1280. On a high density display, the default distance
8559     * is 1920.</p>
8560     *
8561     * <p>If you want to specify a distance that leads to visually consistent
8562     * results across various densities, use the following formula:</p>
8563     * <pre>
8564     * float scale = context.getResources().getDisplayMetrics().density;
8565     * view.setCameraDistance(distance * scale);
8566     * </pre>
8567     *
8568     * <p>The density scale factor of a high density display is 1.5,
8569     * and 1920 = 1280 * 1.5.</p>
8570     *
8571     * @param distance The distance in "depth pixels", if negative the opposite
8572     *        value is used
8573     *
8574     * @see #setRotationX(float)
8575     * @see #setRotationY(float)
8576     */
8577    public void setCameraDistance(float distance) {
8578        invalidateViewProperty(true, false);
8579
8580        ensureTransformationInfo();
8581        final float dpi = mResources.getDisplayMetrics().densityDpi;
8582        final TransformationInfo info = mTransformationInfo;
8583        if (info.mCamera == null) {
8584            info.mCamera = new Camera();
8585            info.matrix3D = new Matrix();
8586        }
8587
8588        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
8589        info.mMatrixDirty = true;
8590
8591        invalidateViewProperty(false, false);
8592        if (mDisplayList != null) {
8593            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
8594        }
8595        if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8596            // View was rejected last time it was drawn by its parent; this may have changed
8597            invalidateParentIfNeeded();
8598        }
8599    }
8600
8601    /**
8602     * The degrees that the view is rotated around the pivot point.
8603     *
8604     * @see #setRotation(float)
8605     * @see #getPivotX()
8606     * @see #getPivotY()
8607     *
8608     * @return The degrees of rotation.
8609     */
8610    @ViewDebug.ExportedProperty(category = "drawing")
8611    public float getRotation() {
8612        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
8613    }
8614
8615    /**
8616     * Sets the degrees that the view is rotated around the pivot point. Increasing values
8617     * result in clockwise rotation.
8618     *
8619     * @param rotation The degrees of rotation.
8620     *
8621     * @see #getRotation()
8622     * @see #getPivotX()
8623     * @see #getPivotY()
8624     * @see #setRotationX(float)
8625     * @see #setRotationY(float)
8626     *
8627     * @attr ref android.R.styleable#View_rotation
8628     */
8629    public void setRotation(float rotation) {
8630        ensureTransformationInfo();
8631        final TransformationInfo info = mTransformationInfo;
8632        if (info.mRotation != rotation) {
8633            // Double-invalidation is necessary to capture view's old and new areas
8634            invalidateViewProperty(true, false);
8635            info.mRotation = rotation;
8636            info.mMatrixDirty = true;
8637            invalidateViewProperty(false, true);
8638            if (mDisplayList != null) {
8639                mDisplayList.setRotation(rotation);
8640            }
8641            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8642                // View was rejected last time it was drawn by its parent; this may have changed
8643                invalidateParentIfNeeded();
8644            }
8645        }
8646    }
8647
8648    /**
8649     * The degrees that the view is rotated around the vertical axis through the pivot point.
8650     *
8651     * @see #getPivotX()
8652     * @see #getPivotY()
8653     * @see #setRotationY(float)
8654     *
8655     * @return The degrees of Y rotation.
8656     */
8657    @ViewDebug.ExportedProperty(category = "drawing")
8658    public float getRotationY() {
8659        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
8660    }
8661
8662    /**
8663     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
8664     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
8665     * down the y axis.
8666     *
8667     * When rotating large views, it is recommended to adjust the camera distance
8668     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8669     *
8670     * @param rotationY The degrees of Y rotation.
8671     *
8672     * @see #getRotationY()
8673     * @see #getPivotX()
8674     * @see #getPivotY()
8675     * @see #setRotation(float)
8676     * @see #setRotationX(float)
8677     * @see #setCameraDistance(float)
8678     *
8679     * @attr ref android.R.styleable#View_rotationY
8680     */
8681    public void setRotationY(float rotationY) {
8682        ensureTransformationInfo();
8683        final TransformationInfo info = mTransformationInfo;
8684        if (info.mRotationY != rotationY) {
8685            invalidateViewProperty(true, false);
8686            info.mRotationY = rotationY;
8687            info.mMatrixDirty = true;
8688            invalidateViewProperty(false, true);
8689            if (mDisplayList != null) {
8690                mDisplayList.setRotationY(rotationY);
8691            }
8692            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8693                // View was rejected last time it was drawn by its parent; this may have changed
8694                invalidateParentIfNeeded();
8695            }
8696        }
8697    }
8698
8699    /**
8700     * The degrees that the view is rotated around the horizontal axis through the pivot point.
8701     *
8702     * @see #getPivotX()
8703     * @see #getPivotY()
8704     * @see #setRotationX(float)
8705     *
8706     * @return The degrees of X rotation.
8707     */
8708    @ViewDebug.ExportedProperty(category = "drawing")
8709    public float getRotationX() {
8710        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
8711    }
8712
8713    /**
8714     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
8715     * Increasing values result in clockwise rotation from the viewpoint of looking down the
8716     * x axis.
8717     *
8718     * When rotating large views, it is recommended to adjust the camera distance
8719     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
8720     *
8721     * @param rotationX The degrees of X rotation.
8722     *
8723     * @see #getRotationX()
8724     * @see #getPivotX()
8725     * @see #getPivotY()
8726     * @see #setRotation(float)
8727     * @see #setRotationY(float)
8728     * @see #setCameraDistance(float)
8729     *
8730     * @attr ref android.R.styleable#View_rotationX
8731     */
8732    public void setRotationX(float rotationX) {
8733        ensureTransformationInfo();
8734        final TransformationInfo info = mTransformationInfo;
8735        if (info.mRotationX != rotationX) {
8736            invalidateViewProperty(true, false);
8737            info.mRotationX = rotationX;
8738            info.mMatrixDirty = true;
8739            invalidateViewProperty(false, true);
8740            if (mDisplayList != null) {
8741                mDisplayList.setRotationX(rotationX);
8742            }
8743            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8744                // View was rejected last time it was drawn by its parent; this may have changed
8745                invalidateParentIfNeeded();
8746            }
8747        }
8748    }
8749
8750    /**
8751     * The amount that the view is scaled in x around the pivot point, as a proportion of
8752     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
8753     *
8754     * <p>By default, this is 1.0f.
8755     *
8756     * @see #getPivotX()
8757     * @see #getPivotY()
8758     * @return The scaling factor.
8759     */
8760    @ViewDebug.ExportedProperty(category = "drawing")
8761    public float getScaleX() {
8762        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
8763    }
8764
8765    /**
8766     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
8767     * the view's unscaled width. A value of 1 means that no scaling is applied.
8768     *
8769     * @param scaleX The scaling factor.
8770     * @see #getPivotX()
8771     * @see #getPivotY()
8772     *
8773     * @attr ref android.R.styleable#View_scaleX
8774     */
8775    public void setScaleX(float scaleX) {
8776        ensureTransformationInfo();
8777        final TransformationInfo info = mTransformationInfo;
8778        if (info.mScaleX != scaleX) {
8779            invalidateViewProperty(true, false);
8780            info.mScaleX = scaleX;
8781            info.mMatrixDirty = true;
8782            invalidateViewProperty(false, true);
8783            if (mDisplayList != null) {
8784                mDisplayList.setScaleX(scaleX);
8785            }
8786            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8787                // View was rejected last time it was drawn by its parent; this may have changed
8788                invalidateParentIfNeeded();
8789            }
8790        }
8791    }
8792
8793    /**
8794     * The amount that the view is scaled in y around the pivot point, as a proportion of
8795     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
8796     *
8797     * <p>By default, this is 1.0f.
8798     *
8799     * @see #getPivotX()
8800     * @see #getPivotY()
8801     * @return The scaling factor.
8802     */
8803    @ViewDebug.ExportedProperty(category = "drawing")
8804    public float getScaleY() {
8805        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
8806    }
8807
8808    /**
8809     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
8810     * the view's unscaled width. A value of 1 means that no scaling is applied.
8811     *
8812     * @param scaleY The scaling factor.
8813     * @see #getPivotX()
8814     * @see #getPivotY()
8815     *
8816     * @attr ref android.R.styleable#View_scaleY
8817     */
8818    public void setScaleY(float scaleY) {
8819        ensureTransformationInfo();
8820        final TransformationInfo info = mTransformationInfo;
8821        if (info.mScaleY != scaleY) {
8822            invalidateViewProperty(true, false);
8823            info.mScaleY = scaleY;
8824            info.mMatrixDirty = true;
8825            invalidateViewProperty(false, true);
8826            if (mDisplayList != null) {
8827                mDisplayList.setScaleY(scaleY);
8828            }
8829            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8830                // View was rejected last time it was drawn by its parent; this may have changed
8831                invalidateParentIfNeeded();
8832            }
8833        }
8834    }
8835
8836    /**
8837     * The x location of the point around which the view is {@link #setRotation(float) rotated}
8838     * and {@link #setScaleX(float) scaled}.
8839     *
8840     * @see #getRotation()
8841     * @see #getScaleX()
8842     * @see #getScaleY()
8843     * @see #getPivotY()
8844     * @return The x location of the pivot point.
8845     *
8846     * @attr ref android.R.styleable#View_transformPivotX
8847     */
8848    @ViewDebug.ExportedProperty(category = "drawing")
8849    public float getPivotX() {
8850        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
8851    }
8852
8853    /**
8854     * Sets the x location of the point around which the view is
8855     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
8856     * By default, the pivot point is centered on the object.
8857     * Setting this property disables this behavior and causes the view to use only the
8858     * explicitly set pivotX and pivotY values.
8859     *
8860     * @param pivotX The x location of the pivot point.
8861     * @see #getRotation()
8862     * @see #getScaleX()
8863     * @see #getScaleY()
8864     * @see #getPivotY()
8865     *
8866     * @attr ref android.R.styleable#View_transformPivotX
8867     */
8868    public void setPivotX(float pivotX) {
8869        ensureTransformationInfo();
8870        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8871        final TransformationInfo info = mTransformationInfo;
8872        if (info.mPivotX != pivotX) {
8873            invalidateViewProperty(true, false);
8874            info.mPivotX = pivotX;
8875            info.mMatrixDirty = true;
8876            invalidateViewProperty(false, true);
8877            if (mDisplayList != null) {
8878                mDisplayList.setPivotX(pivotX);
8879            }
8880            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8881                // View was rejected last time it was drawn by its parent; this may have changed
8882                invalidateParentIfNeeded();
8883            }
8884        }
8885    }
8886
8887    /**
8888     * The y location of the point around which the view is {@link #setRotation(float) rotated}
8889     * and {@link #setScaleY(float) scaled}.
8890     *
8891     * @see #getRotation()
8892     * @see #getScaleX()
8893     * @see #getScaleY()
8894     * @see #getPivotY()
8895     * @return The y location of the pivot point.
8896     *
8897     * @attr ref android.R.styleable#View_transformPivotY
8898     */
8899    @ViewDebug.ExportedProperty(category = "drawing")
8900    public float getPivotY() {
8901        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
8902    }
8903
8904    /**
8905     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
8906     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
8907     * Setting this property disables this behavior and causes the view to use only the
8908     * explicitly set pivotX and pivotY values.
8909     *
8910     * @param pivotY The y location of the pivot point.
8911     * @see #getRotation()
8912     * @see #getScaleX()
8913     * @see #getScaleY()
8914     * @see #getPivotY()
8915     *
8916     * @attr ref android.R.styleable#View_transformPivotY
8917     */
8918    public void setPivotY(float pivotY) {
8919        ensureTransformationInfo();
8920        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
8921        final TransformationInfo info = mTransformationInfo;
8922        if (info.mPivotY != pivotY) {
8923            invalidateViewProperty(true, false);
8924            info.mPivotY = pivotY;
8925            info.mMatrixDirty = true;
8926            invalidateViewProperty(false, true);
8927            if (mDisplayList != null) {
8928                mDisplayList.setPivotY(pivotY);
8929            }
8930            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
8931                // View was rejected last time it was drawn by its parent; this may have changed
8932                invalidateParentIfNeeded();
8933            }
8934        }
8935    }
8936
8937    /**
8938     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
8939     * completely transparent and 1 means the view is completely opaque.
8940     *
8941     * <p>By default this is 1.0f.
8942     * @return The opacity of the view.
8943     */
8944    @ViewDebug.ExportedProperty(category = "drawing")
8945    public float getAlpha() {
8946        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
8947    }
8948
8949    /**
8950     * Returns whether this View has content which overlaps. This function, intended to be
8951     * overridden by specific View types, is an optimization when alpha is set on a view. If
8952     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
8953     * and then composited it into place, which can be expensive. If the view has no overlapping
8954     * rendering, the view can draw each primitive with the appropriate alpha value directly.
8955     * An example of overlapping rendering is a TextView with a background image, such as a
8956     * Button. An example of non-overlapping rendering is a TextView with no background, or
8957     * an ImageView with only the foreground image. The default implementation returns true;
8958     * subclasses should override if they have cases which can be optimized.
8959     *
8960     * @return true if the content in this view might overlap, false otherwise.
8961     */
8962    public boolean hasOverlappingRendering() {
8963        return true;
8964    }
8965
8966    /**
8967     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
8968     * completely transparent and 1 means the view is completely opaque.</p>
8969     *
8970     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
8971     * responsible for applying the opacity itself. Otherwise, calling this method is
8972     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
8973     * setting a hardware layer.</p>
8974     *
8975     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
8976     * performance implications. It is generally best to use the alpha property sparingly and
8977     * transiently, as in the case of fading animations.</p>
8978     *
8979     * @param alpha The opacity of the view.
8980     *
8981     * @see #setLayerType(int, android.graphics.Paint)
8982     *
8983     * @attr ref android.R.styleable#View_alpha
8984     */
8985    public void setAlpha(float alpha) {
8986        ensureTransformationInfo();
8987        if (mTransformationInfo.mAlpha != alpha) {
8988            mTransformationInfo.mAlpha = alpha;
8989            if (onSetAlpha((int) (alpha * 255))) {
8990                mPrivateFlags |= ALPHA_SET;
8991                // subclass is handling alpha - don't optimize rendering cache invalidation
8992                invalidateParentCaches();
8993                invalidate(true);
8994            } else {
8995                mPrivateFlags &= ~ALPHA_SET;
8996                invalidateViewProperty(true, false);
8997                if (mDisplayList != null) {
8998                    mDisplayList.setAlpha(alpha);
8999                }
9000            }
9001        }
9002    }
9003
9004    /**
9005     * Faster version of setAlpha() which performs the same steps except there are
9006     * no calls to invalidate(). The caller of this function should perform proper invalidation
9007     * on the parent and this object. The return value indicates whether the subclass handles
9008     * alpha (the return value for onSetAlpha()).
9009     *
9010     * @param alpha The new value for the alpha property
9011     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9012     *         the new value for the alpha property is different from the old value
9013     */
9014    boolean setAlphaNoInvalidation(float alpha) {
9015        ensureTransformationInfo();
9016        if (mTransformationInfo.mAlpha != alpha) {
9017            mTransformationInfo.mAlpha = alpha;
9018            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9019            if (subclassHandlesAlpha) {
9020                mPrivateFlags |= ALPHA_SET;
9021                return true;
9022            } else {
9023                mPrivateFlags &= ~ALPHA_SET;
9024                if (mDisplayList != null) {
9025                    mDisplayList.setAlpha(alpha);
9026                }
9027            }
9028        }
9029        return false;
9030    }
9031
9032    /**
9033     * Top position of this view relative to its parent.
9034     *
9035     * @return The top of this view, in pixels.
9036     */
9037    @ViewDebug.CapturedViewProperty
9038    public final int getTop() {
9039        return mTop;
9040    }
9041
9042    /**
9043     * Sets the top position of this view relative to its parent. This method is meant to be called
9044     * by the layout system and should not generally be called otherwise, because the property
9045     * may be changed at any time by the layout.
9046     *
9047     * @param top The top of this view, in pixels.
9048     */
9049    public final void setTop(int top) {
9050        if (top != mTop) {
9051            updateMatrix();
9052            final boolean matrixIsIdentity = mTransformationInfo == null
9053                    || mTransformationInfo.mMatrixIsIdentity;
9054            if (matrixIsIdentity) {
9055                if (mAttachInfo != null) {
9056                    int minTop;
9057                    int yLoc;
9058                    if (top < mTop) {
9059                        minTop = top;
9060                        yLoc = top - mTop;
9061                    } else {
9062                        minTop = mTop;
9063                        yLoc = 0;
9064                    }
9065                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9066                }
9067            } else {
9068                // Double-invalidation is necessary to capture view's old and new areas
9069                invalidate(true);
9070            }
9071
9072            int width = mRight - mLeft;
9073            int oldHeight = mBottom - mTop;
9074
9075            mTop = top;
9076            if (mDisplayList != null) {
9077                mDisplayList.setTop(mTop);
9078            }
9079
9080            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9081
9082            if (!matrixIsIdentity) {
9083                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9084                    // A change in dimension means an auto-centered pivot point changes, too
9085                    mTransformationInfo.mMatrixDirty = true;
9086                }
9087                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9088                invalidate(true);
9089            }
9090            mBackgroundSizeChanged = true;
9091            invalidateParentIfNeeded();
9092            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9093                // View was rejected last time it was drawn by its parent; this may have changed
9094                invalidateParentIfNeeded();
9095            }
9096        }
9097    }
9098
9099    /**
9100     * Bottom position of this view relative to its parent.
9101     *
9102     * @return The bottom of this view, in pixels.
9103     */
9104    @ViewDebug.CapturedViewProperty
9105    public final int getBottom() {
9106        return mBottom;
9107    }
9108
9109    /**
9110     * True if this view has changed since the last time being drawn.
9111     *
9112     * @return The dirty state of this view.
9113     */
9114    public boolean isDirty() {
9115        return (mPrivateFlags & DIRTY_MASK) != 0;
9116    }
9117
9118    /**
9119     * Sets the bottom position of this view relative to its parent. This method is meant to be
9120     * called by the layout system and should not generally be called otherwise, because the
9121     * property may be changed at any time by the layout.
9122     *
9123     * @param bottom The bottom of this view, in pixels.
9124     */
9125    public final void setBottom(int bottom) {
9126        if (bottom != mBottom) {
9127            updateMatrix();
9128            final boolean matrixIsIdentity = mTransformationInfo == null
9129                    || mTransformationInfo.mMatrixIsIdentity;
9130            if (matrixIsIdentity) {
9131                if (mAttachInfo != null) {
9132                    int maxBottom;
9133                    if (bottom < mBottom) {
9134                        maxBottom = mBottom;
9135                    } else {
9136                        maxBottom = bottom;
9137                    }
9138                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9139                }
9140            } else {
9141                // Double-invalidation is necessary to capture view's old and new areas
9142                invalidate(true);
9143            }
9144
9145            int width = mRight - mLeft;
9146            int oldHeight = mBottom - mTop;
9147
9148            mBottom = bottom;
9149            if (mDisplayList != null) {
9150                mDisplayList.setBottom(mBottom);
9151            }
9152
9153            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9154
9155            if (!matrixIsIdentity) {
9156                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9157                    // A change in dimension means an auto-centered pivot point changes, too
9158                    mTransformationInfo.mMatrixDirty = true;
9159                }
9160                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9161                invalidate(true);
9162            }
9163            mBackgroundSizeChanged = true;
9164            invalidateParentIfNeeded();
9165            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9166                // View was rejected last time it was drawn by its parent; this may have changed
9167                invalidateParentIfNeeded();
9168            }
9169        }
9170    }
9171
9172    /**
9173     * Left position of this view relative to its parent.
9174     *
9175     * @return The left edge of this view, in pixels.
9176     */
9177    @ViewDebug.CapturedViewProperty
9178    public final int getLeft() {
9179        return mLeft;
9180    }
9181
9182    /**
9183     * Sets the left position of this view relative to its parent. This method is meant to be called
9184     * by the layout system and should not generally be called otherwise, because the property
9185     * may be changed at any time by the layout.
9186     *
9187     * @param left The bottom of this view, in pixels.
9188     */
9189    public final void setLeft(int left) {
9190        if (left != mLeft) {
9191            updateMatrix();
9192            final boolean matrixIsIdentity = mTransformationInfo == null
9193                    || mTransformationInfo.mMatrixIsIdentity;
9194            if (matrixIsIdentity) {
9195                if (mAttachInfo != null) {
9196                    int minLeft;
9197                    int xLoc;
9198                    if (left < mLeft) {
9199                        minLeft = left;
9200                        xLoc = left - mLeft;
9201                    } else {
9202                        minLeft = mLeft;
9203                        xLoc = 0;
9204                    }
9205                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9206                }
9207            } else {
9208                // Double-invalidation is necessary to capture view's old and new areas
9209                invalidate(true);
9210            }
9211
9212            int oldWidth = mRight - mLeft;
9213            int height = mBottom - mTop;
9214
9215            mLeft = left;
9216            if (mDisplayList != null) {
9217                mDisplayList.setLeft(left);
9218            }
9219
9220            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9221
9222            if (!matrixIsIdentity) {
9223                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9224                    // A change in dimension means an auto-centered pivot point changes, too
9225                    mTransformationInfo.mMatrixDirty = true;
9226                }
9227                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9228                invalidate(true);
9229            }
9230            mBackgroundSizeChanged = true;
9231            invalidateParentIfNeeded();
9232            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9233                // View was rejected last time it was drawn by its parent; this may have changed
9234                invalidateParentIfNeeded();
9235            }
9236        }
9237    }
9238
9239    /**
9240     * Right position of this view relative to its parent.
9241     *
9242     * @return The right edge of this view, in pixels.
9243     */
9244    @ViewDebug.CapturedViewProperty
9245    public final int getRight() {
9246        return mRight;
9247    }
9248
9249    /**
9250     * Sets the right position of this view relative to its parent. This method is meant to be called
9251     * by the layout system and should not generally be called otherwise, because the property
9252     * may be changed at any time by the layout.
9253     *
9254     * @param right The bottom of this view, in pixels.
9255     */
9256    public final void setRight(int right) {
9257        if (right != mRight) {
9258            updateMatrix();
9259            final boolean matrixIsIdentity = mTransformationInfo == null
9260                    || mTransformationInfo.mMatrixIsIdentity;
9261            if (matrixIsIdentity) {
9262                if (mAttachInfo != null) {
9263                    int maxRight;
9264                    if (right < mRight) {
9265                        maxRight = mRight;
9266                    } else {
9267                        maxRight = right;
9268                    }
9269                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9270                }
9271            } else {
9272                // Double-invalidation is necessary to capture view's old and new areas
9273                invalidate(true);
9274            }
9275
9276            int oldWidth = mRight - mLeft;
9277            int height = mBottom - mTop;
9278
9279            mRight = right;
9280            if (mDisplayList != null) {
9281                mDisplayList.setRight(mRight);
9282            }
9283
9284            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9285
9286            if (!matrixIsIdentity) {
9287                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9288                    // A change in dimension means an auto-centered pivot point changes, too
9289                    mTransformationInfo.mMatrixDirty = true;
9290                }
9291                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
9292                invalidate(true);
9293            }
9294            mBackgroundSizeChanged = true;
9295            invalidateParentIfNeeded();
9296            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9297                // View was rejected last time it was drawn by its parent; this may have changed
9298                invalidateParentIfNeeded();
9299            }
9300        }
9301    }
9302
9303    /**
9304     * The visual x position of this view, in pixels. This is equivalent to the
9305     * {@link #setTranslationX(float) translationX} property plus the current
9306     * {@link #getLeft() left} property.
9307     *
9308     * @return The visual x position of this view, in pixels.
9309     */
9310    @ViewDebug.ExportedProperty(category = "drawing")
9311    public float getX() {
9312        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9313    }
9314
9315    /**
9316     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9317     * {@link #setTranslationX(float) translationX} property to be the difference between
9318     * the x value passed in and the current {@link #getLeft() left} property.
9319     *
9320     * @param x The visual x position of this view, in pixels.
9321     */
9322    public void setX(float x) {
9323        setTranslationX(x - mLeft);
9324    }
9325
9326    /**
9327     * The visual y position of this view, in pixels. This is equivalent to the
9328     * {@link #setTranslationY(float) translationY} property plus the current
9329     * {@link #getTop() top} property.
9330     *
9331     * @return The visual y position of this view, in pixels.
9332     */
9333    @ViewDebug.ExportedProperty(category = "drawing")
9334    public float getY() {
9335        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9336    }
9337
9338    /**
9339     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9340     * {@link #setTranslationY(float) translationY} property to be the difference between
9341     * the y value passed in and the current {@link #getTop() top} property.
9342     *
9343     * @param y The visual y position of this view, in pixels.
9344     */
9345    public void setY(float y) {
9346        setTranslationY(y - mTop);
9347    }
9348
9349
9350    /**
9351     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9352     * This position is post-layout, in addition to wherever the object's
9353     * layout placed it.
9354     *
9355     * @return The horizontal position of this view relative to its left position, in pixels.
9356     */
9357    @ViewDebug.ExportedProperty(category = "drawing")
9358    public float getTranslationX() {
9359        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9360    }
9361
9362    /**
9363     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9364     * This effectively positions the object post-layout, in addition to wherever the object's
9365     * layout placed it.
9366     *
9367     * @param translationX The horizontal position of this view relative to its left position,
9368     * in pixels.
9369     *
9370     * @attr ref android.R.styleable#View_translationX
9371     */
9372    public void setTranslationX(float translationX) {
9373        ensureTransformationInfo();
9374        final TransformationInfo info = mTransformationInfo;
9375        if (info.mTranslationX != translationX) {
9376            // Double-invalidation is necessary to capture view's old and new areas
9377            invalidateViewProperty(true, false);
9378            info.mTranslationX = translationX;
9379            info.mMatrixDirty = true;
9380            invalidateViewProperty(false, true);
9381            if (mDisplayList != null) {
9382                mDisplayList.setTranslationX(translationX);
9383            }
9384            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9385                // View was rejected last time it was drawn by its parent; this may have changed
9386                invalidateParentIfNeeded();
9387            }
9388        }
9389    }
9390
9391    /**
9392     * The horizontal location of this view relative to its {@link #getTop() top} position.
9393     * This position is post-layout, in addition to wherever the object's
9394     * layout placed it.
9395     *
9396     * @return The vertical position of this view relative to its top position,
9397     * in pixels.
9398     */
9399    @ViewDebug.ExportedProperty(category = "drawing")
9400    public float getTranslationY() {
9401        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9402    }
9403
9404    /**
9405     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9406     * This effectively positions the object post-layout, in addition to wherever the object's
9407     * layout placed it.
9408     *
9409     * @param translationY The vertical position of this view relative to its top position,
9410     * in pixels.
9411     *
9412     * @attr ref android.R.styleable#View_translationY
9413     */
9414    public void setTranslationY(float translationY) {
9415        ensureTransformationInfo();
9416        final TransformationInfo info = mTransformationInfo;
9417        if (info.mTranslationY != translationY) {
9418            invalidateViewProperty(true, false);
9419            info.mTranslationY = translationY;
9420            info.mMatrixDirty = true;
9421            invalidateViewProperty(false, true);
9422            if (mDisplayList != null) {
9423                mDisplayList.setTranslationY(translationY);
9424            }
9425            if ((mPrivateFlags2 & VIEW_QUICK_REJECTED) == VIEW_QUICK_REJECTED) {
9426                // View was rejected last time it was drawn by its parent; this may have changed
9427                invalidateParentIfNeeded();
9428            }
9429        }
9430    }
9431
9432    /**
9433     * Hit rectangle in parent's coordinates
9434     *
9435     * @param outRect The hit rectangle of the view.
9436     */
9437    public void getHitRect(Rect outRect) {
9438        updateMatrix();
9439        final TransformationInfo info = mTransformationInfo;
9440        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9441            outRect.set(mLeft, mTop, mRight, mBottom);
9442        } else {
9443            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9444            tmpRect.set(-info.mPivotX, -info.mPivotY,
9445                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
9446            info.mMatrix.mapRect(tmpRect);
9447            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9448                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9449        }
9450    }
9451
9452    /**
9453     * Determines whether the given point, in local coordinates is inside the view.
9454     */
9455    /*package*/ final boolean pointInView(float localX, float localY) {
9456        return localX >= 0 && localX < (mRight - mLeft)
9457                && localY >= 0 && localY < (mBottom - mTop);
9458    }
9459
9460    /**
9461     * Utility method to determine whether the given point, in local coordinates,
9462     * is inside the view, where the area of the view is expanded by the slop factor.
9463     * This method is called while processing touch-move events to determine if the event
9464     * is still within the view.
9465     */
9466    private boolean pointInView(float localX, float localY, float slop) {
9467        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9468                localY < ((mBottom - mTop) + slop);
9469    }
9470
9471    /**
9472     * When a view has focus and the user navigates away from it, the next view is searched for
9473     * starting from the rectangle filled in by this method.
9474     *
9475     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
9476     * of the view.  However, if your view maintains some idea of internal selection,
9477     * such as a cursor, or a selected row or column, you should override this method and
9478     * fill in a more specific rectangle.
9479     *
9480     * @param r The rectangle to fill in, in this view's coordinates.
9481     */
9482    public void getFocusedRect(Rect r) {
9483        getDrawingRect(r);
9484    }
9485
9486    /**
9487     * If some part of this view is not clipped by any of its parents, then
9488     * return that area in r in global (root) coordinates. To convert r to local
9489     * coordinates (without taking possible View rotations into account), offset
9490     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
9491     * If the view is completely clipped or translated out, return false.
9492     *
9493     * @param r If true is returned, r holds the global coordinates of the
9494     *        visible portion of this view.
9495     * @param globalOffset If true is returned, globalOffset holds the dx,dy
9496     *        between this view and its root. globalOffet may be null.
9497     * @return true if r is non-empty (i.e. part of the view is visible at the
9498     *         root level.
9499     */
9500    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
9501        int width = mRight - mLeft;
9502        int height = mBottom - mTop;
9503        if (width > 0 && height > 0) {
9504            r.set(0, 0, width, height);
9505            if (globalOffset != null) {
9506                globalOffset.set(-mScrollX, -mScrollY);
9507            }
9508            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
9509        }
9510        return false;
9511    }
9512
9513    public final boolean getGlobalVisibleRect(Rect r) {
9514        return getGlobalVisibleRect(r, null);
9515    }
9516
9517    public final boolean getLocalVisibleRect(Rect r) {
9518        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
9519        if (getGlobalVisibleRect(r, offset)) {
9520            r.offset(-offset.x, -offset.y); // make r local
9521            return true;
9522        }
9523        return false;
9524    }
9525
9526    /**
9527     * Offset this view's vertical location by the specified number of pixels.
9528     *
9529     * @param offset the number of pixels to offset the view by
9530     */
9531    public void offsetTopAndBottom(int offset) {
9532        if (offset != 0) {
9533            updateMatrix();
9534            final boolean matrixIsIdentity = mTransformationInfo == null
9535                    || mTransformationInfo.mMatrixIsIdentity;
9536            if (matrixIsIdentity) {
9537                if (mDisplayList != null) {
9538                    invalidateViewProperty(false, false);
9539                } else {
9540                    final ViewParent p = mParent;
9541                    if (p != null && mAttachInfo != null) {
9542                        final Rect r = mAttachInfo.mTmpInvalRect;
9543                        int minTop;
9544                        int maxBottom;
9545                        int yLoc;
9546                        if (offset < 0) {
9547                            minTop = mTop + offset;
9548                            maxBottom = mBottom;
9549                            yLoc = offset;
9550                        } else {
9551                            minTop = mTop;
9552                            maxBottom = mBottom + offset;
9553                            yLoc = 0;
9554                        }
9555                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
9556                        p.invalidateChild(this, r);
9557                    }
9558                }
9559            } else {
9560                invalidateViewProperty(false, false);
9561            }
9562
9563            mTop += offset;
9564            mBottom += offset;
9565            if (mDisplayList != null) {
9566                mDisplayList.offsetTopBottom(offset);
9567                invalidateViewProperty(false, false);
9568            } else {
9569                if (!matrixIsIdentity) {
9570                    invalidateViewProperty(false, true);
9571                }
9572                invalidateParentIfNeeded();
9573            }
9574        }
9575    }
9576
9577    /**
9578     * Offset this view's horizontal location by the specified amount of pixels.
9579     *
9580     * @param offset the numer of pixels to offset the view by
9581     */
9582    public void offsetLeftAndRight(int offset) {
9583        if (offset != 0) {
9584            updateMatrix();
9585            final boolean matrixIsIdentity = mTransformationInfo == null
9586                    || mTransformationInfo.mMatrixIsIdentity;
9587            if (matrixIsIdentity) {
9588                if (mDisplayList != null) {
9589                    invalidateViewProperty(false, false);
9590                } else {
9591                    final ViewParent p = mParent;
9592                    if (p != null && mAttachInfo != null) {
9593                        final Rect r = mAttachInfo.mTmpInvalRect;
9594                        int minLeft;
9595                        int maxRight;
9596                        if (offset < 0) {
9597                            minLeft = mLeft + offset;
9598                            maxRight = mRight;
9599                        } else {
9600                            minLeft = mLeft;
9601                            maxRight = mRight + offset;
9602                        }
9603                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
9604                        p.invalidateChild(this, r);
9605                    }
9606                }
9607            } else {
9608                invalidateViewProperty(false, false);
9609            }
9610
9611            mLeft += offset;
9612            mRight += offset;
9613            if (mDisplayList != null) {
9614                mDisplayList.offsetLeftRight(offset);
9615                invalidateViewProperty(false, false);
9616            } else {
9617                if (!matrixIsIdentity) {
9618                    invalidateViewProperty(false, true);
9619                }
9620                invalidateParentIfNeeded();
9621            }
9622        }
9623    }
9624
9625    /**
9626     * Get the LayoutParams associated with this view. All views should have
9627     * layout parameters. These supply parameters to the <i>parent</i> of this
9628     * view specifying how it should be arranged. There are many subclasses of
9629     * ViewGroup.LayoutParams, and these correspond to the different subclasses
9630     * of ViewGroup that are responsible for arranging their children.
9631     *
9632     * This method may return null if this View is not attached to a parent
9633     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
9634     * was not invoked successfully. When a View is attached to a parent
9635     * ViewGroup, this method must not return null.
9636     *
9637     * @return The LayoutParams associated with this view, or null if no
9638     *         parameters have been set yet
9639     */
9640    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
9641    public ViewGroup.LayoutParams getLayoutParams() {
9642        return mLayoutParams;
9643    }
9644
9645    /**
9646     * Set the layout parameters associated with this view. These supply
9647     * parameters to the <i>parent</i> of this view specifying how it should be
9648     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
9649     * correspond to the different subclasses of ViewGroup that are responsible
9650     * for arranging their children.
9651     *
9652     * @param params The layout parameters for this view, cannot be null
9653     */
9654    public void setLayoutParams(ViewGroup.LayoutParams params) {
9655        if (params == null) {
9656            throw new NullPointerException("Layout parameters cannot be null");
9657        }
9658        mLayoutParams = params;
9659        if (mParent instanceof ViewGroup) {
9660            ((ViewGroup) mParent).onSetLayoutParams(this, params);
9661        }
9662        requestLayout();
9663    }
9664
9665    /**
9666     * Set the scrolled position of your view. This will cause a call to
9667     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9668     * invalidated.
9669     * @param x the x position to scroll to
9670     * @param y the y position to scroll to
9671     */
9672    public void scrollTo(int x, int y) {
9673        if (mScrollX != x || mScrollY != y) {
9674            int oldX = mScrollX;
9675            int oldY = mScrollY;
9676            mScrollX = x;
9677            mScrollY = y;
9678            invalidateParentCaches();
9679            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
9680            if (!awakenScrollBars()) {
9681                postInvalidateOnAnimation();
9682            }
9683        }
9684    }
9685
9686    /**
9687     * Move the scrolled position of your view. This will cause a call to
9688     * {@link #onScrollChanged(int, int, int, int)} and the view will be
9689     * invalidated.
9690     * @param x the amount of pixels to scroll by horizontally
9691     * @param y the amount of pixels to scroll by vertically
9692     */
9693    public void scrollBy(int x, int y) {
9694        scrollTo(mScrollX + x, mScrollY + y);
9695    }
9696
9697    /**
9698     * <p>Trigger the scrollbars to draw. When invoked this method starts an
9699     * animation to fade the scrollbars out after a default delay. If a subclass
9700     * provides animated scrolling, the start delay should equal the duration
9701     * of the scrolling animation.</p>
9702     *
9703     * <p>The animation starts only if at least one of the scrollbars is
9704     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
9705     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9706     * this method returns true, and false otherwise. If the animation is
9707     * started, this method calls {@link #invalidate()}; in that case the
9708     * caller should not call {@link #invalidate()}.</p>
9709     *
9710     * <p>This method should be invoked every time a subclass directly updates
9711     * the scroll parameters.</p>
9712     *
9713     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
9714     * and {@link #scrollTo(int, int)}.</p>
9715     *
9716     * @return true if the animation is played, false otherwise
9717     *
9718     * @see #awakenScrollBars(int)
9719     * @see #scrollBy(int, int)
9720     * @see #scrollTo(int, int)
9721     * @see #isHorizontalScrollBarEnabled()
9722     * @see #isVerticalScrollBarEnabled()
9723     * @see #setHorizontalScrollBarEnabled(boolean)
9724     * @see #setVerticalScrollBarEnabled(boolean)
9725     */
9726    protected boolean awakenScrollBars() {
9727        return mScrollCache != null &&
9728                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
9729    }
9730
9731    /**
9732     * Trigger the scrollbars to draw.
9733     * This method differs from awakenScrollBars() only in its default duration.
9734     * initialAwakenScrollBars() will show the scroll bars for longer than
9735     * usual to give the user more of a chance to notice them.
9736     *
9737     * @return true if the animation is played, false otherwise.
9738     */
9739    private boolean initialAwakenScrollBars() {
9740        return mScrollCache != null &&
9741                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
9742    }
9743
9744    /**
9745     * <p>
9746     * Trigger the scrollbars to draw. When invoked this method starts an
9747     * animation to fade the scrollbars out after a fixed delay. If a subclass
9748     * provides animated scrolling, the start delay should equal the duration of
9749     * the scrolling animation.
9750     * </p>
9751     *
9752     * <p>
9753     * The animation starts only if at least one of the scrollbars is enabled,
9754     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9755     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9756     * this method returns true, and false otherwise. If the animation is
9757     * started, this method calls {@link #invalidate()}; in that case the caller
9758     * should not call {@link #invalidate()}.
9759     * </p>
9760     *
9761     * <p>
9762     * This method should be invoked everytime a subclass directly updates the
9763     * scroll parameters.
9764     * </p>
9765     *
9766     * @param startDelay the delay, in milliseconds, after which the animation
9767     *        should start; when the delay is 0, the animation starts
9768     *        immediately
9769     * @return true if the animation is played, false otherwise
9770     *
9771     * @see #scrollBy(int, int)
9772     * @see #scrollTo(int, int)
9773     * @see #isHorizontalScrollBarEnabled()
9774     * @see #isVerticalScrollBarEnabled()
9775     * @see #setHorizontalScrollBarEnabled(boolean)
9776     * @see #setVerticalScrollBarEnabled(boolean)
9777     */
9778    protected boolean awakenScrollBars(int startDelay) {
9779        return awakenScrollBars(startDelay, true);
9780    }
9781
9782    /**
9783     * <p>
9784     * Trigger the scrollbars to draw. When invoked this method starts an
9785     * animation to fade the scrollbars out after a fixed delay. If a subclass
9786     * provides animated scrolling, the start delay should equal the duration of
9787     * the scrolling animation.
9788     * </p>
9789     *
9790     * <p>
9791     * The animation starts only if at least one of the scrollbars is enabled,
9792     * as specified by {@link #isHorizontalScrollBarEnabled()} and
9793     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
9794     * this method returns true, and false otherwise. If the animation is
9795     * started, this method calls {@link #invalidate()} if the invalidate parameter
9796     * is set to true; in that case the caller
9797     * should not call {@link #invalidate()}.
9798     * </p>
9799     *
9800     * <p>
9801     * This method should be invoked everytime a subclass directly updates the
9802     * scroll parameters.
9803     * </p>
9804     *
9805     * @param startDelay the delay, in milliseconds, after which the animation
9806     *        should start; when the delay is 0, the animation starts
9807     *        immediately
9808     *
9809     * @param invalidate Wheter this method should call invalidate
9810     *
9811     * @return true if the animation is played, false otherwise
9812     *
9813     * @see #scrollBy(int, int)
9814     * @see #scrollTo(int, int)
9815     * @see #isHorizontalScrollBarEnabled()
9816     * @see #isVerticalScrollBarEnabled()
9817     * @see #setHorizontalScrollBarEnabled(boolean)
9818     * @see #setVerticalScrollBarEnabled(boolean)
9819     */
9820    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
9821        final ScrollabilityCache scrollCache = mScrollCache;
9822
9823        if (scrollCache == null || !scrollCache.fadeScrollBars) {
9824            return false;
9825        }
9826
9827        if (scrollCache.scrollBar == null) {
9828            scrollCache.scrollBar = new ScrollBarDrawable();
9829        }
9830
9831        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
9832
9833            if (invalidate) {
9834                // Invalidate to show the scrollbars
9835                postInvalidateOnAnimation();
9836            }
9837
9838            if (scrollCache.state == ScrollabilityCache.OFF) {
9839                // FIXME: this is copied from WindowManagerService.
9840                // We should get this value from the system when it
9841                // is possible to do so.
9842                final int KEY_REPEAT_FIRST_DELAY = 750;
9843                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
9844            }
9845
9846            // Tell mScrollCache when we should start fading. This may
9847            // extend the fade start time if one was already scheduled
9848            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
9849            scrollCache.fadeStartTime = fadeStartTime;
9850            scrollCache.state = ScrollabilityCache.ON;
9851
9852            // Schedule our fader to run, unscheduling any old ones first
9853            if (mAttachInfo != null) {
9854                mAttachInfo.mHandler.removeCallbacks(scrollCache);
9855                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
9856            }
9857
9858            return true;
9859        }
9860
9861        return false;
9862    }
9863
9864    /**
9865     * Do not invalidate views which are not visible and which are not running an animation. They
9866     * will not get drawn and they should not set dirty flags as if they will be drawn
9867     */
9868    private boolean skipInvalidate() {
9869        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
9870                (!(mParent instanceof ViewGroup) ||
9871                        !((ViewGroup) mParent).isViewTransitioning(this));
9872    }
9873    /**
9874     * Mark the area defined by dirty as needing to be drawn. If the view is
9875     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
9876     * in the future. This must be called from a UI thread. To call from a non-UI
9877     * thread, call {@link #postInvalidate()}.
9878     *
9879     * WARNING: This method is destructive to dirty.
9880     * @param dirty the rectangle representing the bounds of the dirty region
9881     */
9882    public void invalidate(Rect dirty) {
9883        if (skipInvalidate()) {
9884            return;
9885        }
9886        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9887                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9888                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9889            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9890            mPrivateFlags |= INVALIDATED;
9891            mPrivateFlags |= DIRTY;
9892            final ViewParent p = mParent;
9893            final AttachInfo ai = mAttachInfo;
9894            //noinspection PointlessBooleanExpression,ConstantConditions
9895            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9896                if (p != null && ai != null && ai.mHardwareAccelerated) {
9897                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9898                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9899                    p.invalidateChild(this, null);
9900                    return;
9901                }
9902            }
9903            if (p != null && ai != null) {
9904                final int scrollX = mScrollX;
9905                final int scrollY = mScrollY;
9906                final Rect r = ai.mTmpInvalRect;
9907                r.set(dirty.left - scrollX, dirty.top - scrollY,
9908                        dirty.right - scrollX, dirty.bottom - scrollY);
9909                mParent.invalidateChild(this, r);
9910            }
9911        }
9912    }
9913
9914    /**
9915     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
9916     * The coordinates of the dirty rect are relative to the view.
9917     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
9918     * will be called at some point in the future. This must be called from
9919     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
9920     * @param l the left position of the dirty region
9921     * @param t the top position of the dirty region
9922     * @param r the right position of the dirty region
9923     * @param b the bottom position of the dirty region
9924     */
9925    public void invalidate(int l, int t, int r, int b) {
9926        if (skipInvalidate()) {
9927            return;
9928        }
9929        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9930                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
9931                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
9932            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9933            mPrivateFlags |= INVALIDATED;
9934            mPrivateFlags |= DIRTY;
9935            final ViewParent p = mParent;
9936            final AttachInfo ai = mAttachInfo;
9937            //noinspection PointlessBooleanExpression,ConstantConditions
9938            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9939                if (p != null && ai != null && ai.mHardwareAccelerated) {
9940                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9941                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9942                    p.invalidateChild(this, null);
9943                    return;
9944                }
9945            }
9946            if (p != null && ai != null && l < r && t < b) {
9947                final int scrollX = mScrollX;
9948                final int scrollY = mScrollY;
9949                final Rect tmpr = ai.mTmpInvalRect;
9950                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
9951                p.invalidateChild(this, tmpr);
9952            }
9953        }
9954    }
9955
9956    /**
9957     * Invalidate the whole view. If the view is visible,
9958     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
9959     * the future. This must be called from a UI thread. To call from a non-UI thread,
9960     * call {@link #postInvalidate()}.
9961     */
9962    public void invalidate() {
9963        invalidate(true);
9964    }
9965
9966    /**
9967     * This is where the invalidate() work actually happens. A full invalidate()
9968     * causes the drawing cache to be invalidated, but this function can be called with
9969     * invalidateCache set to false to skip that invalidation step for cases that do not
9970     * need it (for example, a component that remains at the same dimensions with the same
9971     * content).
9972     *
9973     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
9974     * well. This is usually true for a full invalidate, but may be set to false if the
9975     * View's contents or dimensions have not changed.
9976     */
9977    void invalidate(boolean invalidateCache) {
9978        if (skipInvalidate()) {
9979            return;
9980        }
9981        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
9982                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
9983                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
9984            mLastIsOpaque = isOpaque();
9985            mPrivateFlags &= ~DRAWN;
9986            mPrivateFlags |= DIRTY;
9987            if (invalidateCache) {
9988                mPrivateFlags |= INVALIDATED;
9989                mPrivateFlags &= ~DRAWING_CACHE_VALID;
9990            }
9991            final AttachInfo ai = mAttachInfo;
9992            final ViewParent p = mParent;
9993            //noinspection PointlessBooleanExpression,ConstantConditions
9994            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
9995                if (p != null && ai != null && ai.mHardwareAccelerated) {
9996                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
9997                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
9998                    p.invalidateChild(this, null);
9999                    return;
10000                }
10001            }
10002
10003            if (p != null && ai != null) {
10004                final Rect r = ai.mTmpInvalRect;
10005                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10006                // Don't call invalidate -- we don't want to internally scroll
10007                // our own bounds
10008                p.invalidateChild(this, r);
10009            }
10010        }
10011    }
10012
10013    /**
10014     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10015     * set any flags or handle all of the cases handled by the default invalidation methods.
10016     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10017     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10018     * walk up the hierarchy, transforming the dirty rect as necessary.
10019     *
10020     * The method also handles normal invalidation logic if display list properties are not
10021     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10022     * backup approach, to handle these cases used in the various property-setting methods.
10023     *
10024     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10025     * are not being used in this view
10026     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10027     * list properties are not being used in this view
10028     */
10029    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10030        if (mDisplayList == null || (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
10031            if (invalidateParent) {
10032                invalidateParentCaches();
10033            }
10034            if (forceRedraw) {
10035                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
10036            }
10037            invalidate(false);
10038        } else {
10039            final AttachInfo ai = mAttachInfo;
10040            final ViewParent p = mParent;
10041            if (p != null && ai != null) {
10042                final Rect r = ai.mTmpInvalRect;
10043                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10044                if (mParent instanceof ViewGroup) {
10045                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10046                } else {
10047                    mParent.invalidateChild(this, r);
10048                }
10049            }
10050        }
10051    }
10052
10053    /**
10054     * Utility method to transform a given Rect by the current matrix of this view.
10055     */
10056    void transformRect(final Rect rect) {
10057        if (!getMatrix().isIdentity()) {
10058            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10059            boundingRect.set(rect);
10060            getMatrix().mapRect(boundingRect);
10061            rect.set((int) (boundingRect.left - 0.5f),
10062                    (int) (boundingRect.top - 0.5f),
10063                    (int) (boundingRect.right + 0.5f),
10064                    (int) (boundingRect.bottom + 0.5f));
10065        }
10066    }
10067
10068    /**
10069     * Used to indicate that the parent of this view should clear its caches. This functionality
10070     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10071     * which is necessary when various parent-managed properties of the view change, such as
10072     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10073     * clears the parent caches and does not causes an invalidate event.
10074     *
10075     * @hide
10076     */
10077    protected void invalidateParentCaches() {
10078        if (mParent instanceof View) {
10079            ((View) mParent).mPrivateFlags |= INVALIDATED;
10080        }
10081    }
10082
10083    /**
10084     * Used to indicate that the parent of this view should be invalidated. This functionality
10085     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10086     * which is necessary when various parent-managed properties of the view change, such as
10087     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10088     * an invalidation event to the parent.
10089     *
10090     * @hide
10091     */
10092    protected void invalidateParentIfNeeded() {
10093        if (isHardwareAccelerated() && mParent instanceof View) {
10094            ((View) mParent).invalidate(true);
10095        }
10096    }
10097
10098    /**
10099     * Indicates whether this View is opaque. An opaque View guarantees that it will
10100     * draw all the pixels overlapping its bounds using a fully opaque color.
10101     *
10102     * Subclasses of View should override this method whenever possible to indicate
10103     * whether an instance is opaque. Opaque Views are treated in a special way by
10104     * the View hierarchy, possibly allowing it to perform optimizations during
10105     * invalidate/draw passes.
10106     *
10107     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10108     */
10109    @ViewDebug.ExportedProperty(category = "drawing")
10110    public boolean isOpaque() {
10111        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
10112                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10113    }
10114
10115    /**
10116     * @hide
10117     */
10118    protected void computeOpaqueFlags() {
10119        // Opaque if:
10120        //   - Has a background
10121        //   - Background is opaque
10122        //   - Doesn't have scrollbars or scrollbars are inside overlay
10123
10124        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10125            mPrivateFlags |= OPAQUE_BACKGROUND;
10126        } else {
10127            mPrivateFlags &= ~OPAQUE_BACKGROUND;
10128        }
10129
10130        final int flags = mViewFlags;
10131        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10132                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10133            mPrivateFlags |= OPAQUE_SCROLLBARS;
10134        } else {
10135            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
10136        }
10137    }
10138
10139    /**
10140     * @hide
10141     */
10142    protected boolean hasOpaqueScrollbars() {
10143        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
10144    }
10145
10146    /**
10147     * @return A handler associated with the thread running the View. This
10148     * handler can be used to pump events in the UI events queue.
10149     */
10150    public Handler getHandler() {
10151        if (mAttachInfo != null) {
10152            return mAttachInfo.mHandler;
10153        }
10154        return null;
10155    }
10156
10157    /**
10158     * Gets the view root associated with the View.
10159     * @return The view root, or null if none.
10160     * @hide
10161     */
10162    public ViewRootImpl getViewRootImpl() {
10163        if (mAttachInfo != null) {
10164            return mAttachInfo.mViewRootImpl;
10165        }
10166        return null;
10167    }
10168
10169    /**
10170     * <p>Causes the Runnable to be added to the message queue.
10171     * The runnable will be run on the user interface thread.</p>
10172     *
10173     * <p>This method can be invoked from outside of the UI thread
10174     * only when this View is attached to a window.</p>
10175     *
10176     * @param action The Runnable that will be executed.
10177     *
10178     * @return Returns true if the Runnable was successfully placed in to the
10179     *         message queue.  Returns false on failure, usually because the
10180     *         looper processing the message queue is exiting.
10181     *
10182     * @see #postDelayed
10183     * @see #removeCallbacks
10184     */
10185    public boolean post(Runnable action) {
10186        final AttachInfo attachInfo = mAttachInfo;
10187        if (attachInfo != null) {
10188            return attachInfo.mHandler.post(action);
10189        }
10190        // Assume that post will succeed later
10191        ViewRootImpl.getRunQueue().post(action);
10192        return true;
10193    }
10194
10195    /**
10196     * <p>Causes the Runnable to be added to the message queue, to be run
10197     * after the specified amount of time elapses.
10198     * The runnable will be run on the user interface thread.</p>
10199     *
10200     * <p>This method can be invoked from outside of the UI thread
10201     * only when this View is attached to a window.</p>
10202     *
10203     * @param action The Runnable that will be executed.
10204     * @param delayMillis The delay (in milliseconds) until the Runnable
10205     *        will be executed.
10206     *
10207     * @return true if the Runnable was successfully placed in to the
10208     *         message queue.  Returns false on failure, usually because the
10209     *         looper processing the message queue is exiting.  Note that a
10210     *         result of true does not mean the Runnable will be processed --
10211     *         if the looper is quit before the delivery time of the message
10212     *         occurs then the message will be dropped.
10213     *
10214     * @see #post
10215     * @see #removeCallbacks
10216     */
10217    public boolean postDelayed(Runnable action, long delayMillis) {
10218        final AttachInfo attachInfo = mAttachInfo;
10219        if (attachInfo != null) {
10220            return attachInfo.mHandler.postDelayed(action, delayMillis);
10221        }
10222        // Assume that post will succeed later
10223        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10224        return true;
10225    }
10226
10227    /**
10228     * <p>Causes the Runnable to execute on the next animation time step.
10229     * The runnable will be run on the user interface thread.</p>
10230     *
10231     * <p>This method can be invoked from outside of the UI thread
10232     * only when this View is attached to a window.</p>
10233     *
10234     * @param action The Runnable that will be executed.
10235     *
10236     * @see #postOnAnimationDelayed
10237     * @see #removeCallbacks
10238     */
10239    public void postOnAnimation(Runnable action) {
10240        final AttachInfo attachInfo = mAttachInfo;
10241        if (attachInfo != null) {
10242            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10243                    Choreographer.CALLBACK_ANIMATION, action, null);
10244        } else {
10245            // Assume that post will succeed later
10246            ViewRootImpl.getRunQueue().post(action);
10247        }
10248    }
10249
10250    /**
10251     * <p>Causes the Runnable to execute on the next animation time step,
10252     * after the specified amount of time elapses.
10253     * The runnable will be run on the user interface thread.</p>
10254     *
10255     * <p>This method can be invoked from outside of the UI thread
10256     * only when this View is attached to a window.</p>
10257     *
10258     * @param action The Runnable that will be executed.
10259     * @param delayMillis The delay (in milliseconds) until the Runnable
10260     *        will be executed.
10261     *
10262     * @see #postOnAnimation
10263     * @see #removeCallbacks
10264     */
10265    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10266        final AttachInfo attachInfo = mAttachInfo;
10267        if (attachInfo != null) {
10268            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10269                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10270        } else {
10271            // Assume that post will succeed later
10272            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10273        }
10274    }
10275
10276    /**
10277     * <p>Removes the specified Runnable from the message queue.</p>
10278     *
10279     * <p>This method can be invoked from outside of the UI thread
10280     * only when this View is attached to a window.</p>
10281     *
10282     * @param action The Runnable to remove from the message handling queue
10283     *
10284     * @return true if this view could ask the Handler to remove the Runnable,
10285     *         false otherwise. When the returned value is true, the Runnable
10286     *         may or may not have been actually removed from the message queue
10287     *         (for instance, if the Runnable was not in the queue already.)
10288     *
10289     * @see #post
10290     * @see #postDelayed
10291     * @see #postOnAnimation
10292     * @see #postOnAnimationDelayed
10293     */
10294    public boolean removeCallbacks(Runnable action) {
10295        if (action != null) {
10296            final AttachInfo attachInfo = mAttachInfo;
10297            if (attachInfo != null) {
10298                attachInfo.mHandler.removeCallbacks(action);
10299                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10300                        Choreographer.CALLBACK_ANIMATION, action, null);
10301            } else {
10302                // Assume that post will succeed later
10303                ViewRootImpl.getRunQueue().removeCallbacks(action);
10304            }
10305        }
10306        return true;
10307    }
10308
10309    /**
10310     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10311     * Use this to invalidate the View from a non-UI thread.</p>
10312     *
10313     * <p>This method can be invoked from outside of the UI thread
10314     * only when this View is attached to a window.</p>
10315     *
10316     * @see #invalidate()
10317     * @see #postInvalidateDelayed(long)
10318     */
10319    public void postInvalidate() {
10320        postInvalidateDelayed(0);
10321    }
10322
10323    /**
10324     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10325     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10326     *
10327     * <p>This method can be invoked from outside of the UI thread
10328     * only when this View is attached to a window.</p>
10329     *
10330     * @param left The left coordinate of the rectangle to invalidate.
10331     * @param top The top coordinate of the rectangle to invalidate.
10332     * @param right The right coordinate of the rectangle to invalidate.
10333     * @param bottom The bottom coordinate of the rectangle to invalidate.
10334     *
10335     * @see #invalidate(int, int, int, int)
10336     * @see #invalidate(Rect)
10337     * @see #postInvalidateDelayed(long, int, int, int, int)
10338     */
10339    public void postInvalidate(int left, int top, int right, int bottom) {
10340        postInvalidateDelayed(0, left, top, right, bottom);
10341    }
10342
10343    /**
10344     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10345     * loop. Waits for the specified amount of time.</p>
10346     *
10347     * <p>This method can be invoked from outside of the UI thread
10348     * only when this View is attached to a window.</p>
10349     *
10350     * @param delayMilliseconds the duration in milliseconds to delay the
10351     *         invalidation by
10352     *
10353     * @see #invalidate()
10354     * @see #postInvalidate()
10355     */
10356    public void postInvalidateDelayed(long delayMilliseconds) {
10357        // We try only with the AttachInfo because there's no point in invalidating
10358        // if we are not attached to our window
10359        final AttachInfo attachInfo = mAttachInfo;
10360        if (attachInfo != null) {
10361            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10362        }
10363    }
10364
10365    /**
10366     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10367     * through the event loop. Waits for the specified amount of time.</p>
10368     *
10369     * <p>This method can be invoked from outside of the UI thread
10370     * only when this View is attached to a window.</p>
10371     *
10372     * @param delayMilliseconds the duration in milliseconds to delay the
10373     *         invalidation by
10374     * @param left The left coordinate of the rectangle to invalidate.
10375     * @param top The top coordinate of the rectangle to invalidate.
10376     * @param right The right coordinate of the rectangle to invalidate.
10377     * @param bottom The bottom coordinate of the rectangle to invalidate.
10378     *
10379     * @see #invalidate(int, int, int, int)
10380     * @see #invalidate(Rect)
10381     * @see #postInvalidate(int, int, int, int)
10382     */
10383    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10384            int right, int bottom) {
10385
10386        // We try only with the AttachInfo because there's no point in invalidating
10387        // if we are not attached to our window
10388        final AttachInfo attachInfo = mAttachInfo;
10389        if (attachInfo != null) {
10390            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10391            info.target = this;
10392            info.left = left;
10393            info.top = top;
10394            info.right = right;
10395            info.bottom = bottom;
10396
10397            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10398        }
10399    }
10400
10401    /**
10402     * <p>Cause an invalidate to happen on the next animation time step, typically the
10403     * next display frame.</p>
10404     *
10405     * <p>This method can be invoked from outside of the UI thread
10406     * only when this View is attached to a window.</p>
10407     *
10408     * @see #invalidate()
10409     */
10410    public void postInvalidateOnAnimation() {
10411        // We try only with the AttachInfo because there's no point in invalidating
10412        // if we are not attached to our window
10413        final AttachInfo attachInfo = mAttachInfo;
10414        if (attachInfo != null) {
10415            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10416        }
10417    }
10418
10419    /**
10420     * <p>Cause an invalidate of the specified area to happen on the next animation
10421     * time step, typically the next display frame.</p>
10422     *
10423     * <p>This method can be invoked from outside of the UI thread
10424     * only when this View is attached to a window.</p>
10425     *
10426     * @param left The left coordinate of the rectangle to invalidate.
10427     * @param top The top coordinate of the rectangle to invalidate.
10428     * @param right The right coordinate of the rectangle to invalidate.
10429     * @param bottom The bottom coordinate of the rectangle to invalidate.
10430     *
10431     * @see #invalidate(int, int, int, int)
10432     * @see #invalidate(Rect)
10433     */
10434    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10435        // We try only with the AttachInfo because there's no point in invalidating
10436        // if we are not attached to our window
10437        final AttachInfo attachInfo = mAttachInfo;
10438        if (attachInfo != null) {
10439            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
10440            info.target = this;
10441            info.left = left;
10442            info.top = top;
10443            info.right = right;
10444            info.bottom = bottom;
10445
10446            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10447        }
10448    }
10449
10450    /**
10451     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10452     * This event is sent at most once every
10453     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10454     */
10455    private void postSendViewScrolledAccessibilityEventCallback() {
10456        if (mSendViewScrolledAccessibilityEvent == null) {
10457            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10458        }
10459        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10460            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10461            postDelayed(mSendViewScrolledAccessibilityEvent,
10462                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10463        }
10464    }
10465
10466    /**
10467     * Called by a parent to request that a child update its values for mScrollX
10468     * and mScrollY if necessary. This will typically be done if the child is
10469     * animating a scroll using a {@link android.widget.Scroller Scroller}
10470     * object.
10471     */
10472    public void computeScroll() {
10473    }
10474
10475    /**
10476     * <p>Indicate whether the horizontal edges are faded when the view is
10477     * scrolled horizontally.</p>
10478     *
10479     * @return true if the horizontal edges should are faded on scroll, false
10480     *         otherwise
10481     *
10482     * @see #setHorizontalFadingEdgeEnabled(boolean)
10483     *
10484     * @attr ref android.R.styleable#View_requiresFadingEdge
10485     */
10486    public boolean isHorizontalFadingEdgeEnabled() {
10487        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10488    }
10489
10490    /**
10491     * <p>Define whether the horizontal edges should be faded when this view
10492     * is scrolled horizontally.</p>
10493     *
10494     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
10495     *                                    be faded when the view is scrolled
10496     *                                    horizontally
10497     *
10498     * @see #isHorizontalFadingEdgeEnabled()
10499     *
10500     * @attr ref android.R.styleable#View_requiresFadingEdge
10501     */
10502    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
10503        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
10504            if (horizontalFadingEdgeEnabled) {
10505                initScrollCache();
10506            }
10507
10508            mViewFlags ^= FADING_EDGE_HORIZONTAL;
10509        }
10510    }
10511
10512    /**
10513     * <p>Indicate whether the vertical edges are faded when the view is
10514     * scrolled horizontally.</p>
10515     *
10516     * @return true if the vertical edges should are faded on scroll, false
10517     *         otherwise
10518     *
10519     * @see #setVerticalFadingEdgeEnabled(boolean)
10520     *
10521     * @attr ref android.R.styleable#View_requiresFadingEdge
10522     */
10523    public boolean isVerticalFadingEdgeEnabled() {
10524        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
10525    }
10526
10527    /**
10528     * <p>Define whether the vertical edges should be faded when this view
10529     * is scrolled vertically.</p>
10530     *
10531     * @param verticalFadingEdgeEnabled true if the vertical edges should
10532     *                                  be faded when the view is scrolled
10533     *                                  vertically
10534     *
10535     * @see #isVerticalFadingEdgeEnabled()
10536     *
10537     * @attr ref android.R.styleable#View_requiresFadingEdge
10538     */
10539    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
10540        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
10541            if (verticalFadingEdgeEnabled) {
10542                initScrollCache();
10543            }
10544
10545            mViewFlags ^= FADING_EDGE_VERTICAL;
10546        }
10547    }
10548
10549    /**
10550     * Returns the strength, or intensity, of the top faded edge. The strength is
10551     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10552     * returns 0.0 or 1.0 but no value in between.
10553     *
10554     * Subclasses should override this method to provide a smoother fade transition
10555     * when scrolling occurs.
10556     *
10557     * @return the intensity of the top fade as a float between 0.0f and 1.0f
10558     */
10559    protected float getTopFadingEdgeStrength() {
10560        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
10561    }
10562
10563    /**
10564     * Returns the strength, or intensity, of the bottom faded edge. The strength is
10565     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10566     * returns 0.0 or 1.0 but no value in between.
10567     *
10568     * Subclasses should override this method to provide a smoother fade transition
10569     * when scrolling occurs.
10570     *
10571     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
10572     */
10573    protected float getBottomFadingEdgeStrength() {
10574        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
10575                computeVerticalScrollRange() ? 1.0f : 0.0f;
10576    }
10577
10578    /**
10579     * Returns the strength, or intensity, of the left faded edge. The strength is
10580     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10581     * returns 0.0 or 1.0 but no value in between.
10582     *
10583     * Subclasses should override this method to provide a smoother fade transition
10584     * when scrolling occurs.
10585     *
10586     * @return the intensity of the left fade as a float between 0.0f and 1.0f
10587     */
10588    protected float getLeftFadingEdgeStrength() {
10589        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
10590    }
10591
10592    /**
10593     * Returns the strength, or intensity, of the right faded edge. The strength is
10594     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
10595     * returns 0.0 or 1.0 but no value in between.
10596     *
10597     * Subclasses should override this method to provide a smoother fade transition
10598     * when scrolling occurs.
10599     *
10600     * @return the intensity of the right fade as a float between 0.0f and 1.0f
10601     */
10602    protected float getRightFadingEdgeStrength() {
10603        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
10604                computeHorizontalScrollRange() ? 1.0f : 0.0f;
10605    }
10606
10607    /**
10608     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
10609     * scrollbar is not drawn by default.</p>
10610     *
10611     * @return true if the horizontal scrollbar should be painted, false
10612     *         otherwise
10613     *
10614     * @see #setHorizontalScrollBarEnabled(boolean)
10615     */
10616    public boolean isHorizontalScrollBarEnabled() {
10617        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
10618    }
10619
10620    /**
10621     * <p>Define whether the horizontal scrollbar should be drawn or not. The
10622     * scrollbar is not drawn by default.</p>
10623     *
10624     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
10625     *                                   be painted
10626     *
10627     * @see #isHorizontalScrollBarEnabled()
10628     */
10629    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
10630        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
10631            mViewFlags ^= SCROLLBARS_HORIZONTAL;
10632            computeOpaqueFlags();
10633            resolvePadding();
10634        }
10635    }
10636
10637    /**
10638     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
10639     * scrollbar is not drawn by default.</p>
10640     *
10641     * @return true if the vertical scrollbar should be painted, false
10642     *         otherwise
10643     *
10644     * @see #setVerticalScrollBarEnabled(boolean)
10645     */
10646    public boolean isVerticalScrollBarEnabled() {
10647        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
10648    }
10649
10650    /**
10651     * <p>Define whether the vertical scrollbar should be drawn or not. The
10652     * scrollbar is not drawn by default.</p>
10653     *
10654     * @param verticalScrollBarEnabled true if the vertical scrollbar should
10655     *                                 be painted
10656     *
10657     * @see #isVerticalScrollBarEnabled()
10658     */
10659    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
10660        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
10661            mViewFlags ^= SCROLLBARS_VERTICAL;
10662            computeOpaqueFlags();
10663            resolvePadding();
10664        }
10665    }
10666
10667    /**
10668     * @hide
10669     */
10670    protected void recomputePadding() {
10671        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
10672    }
10673
10674    /**
10675     * Define whether scrollbars will fade when the view is not scrolling.
10676     *
10677     * @param fadeScrollbars wheter to enable fading
10678     *
10679     * @attr ref android.R.styleable#View_fadeScrollbars
10680     */
10681    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
10682        initScrollCache();
10683        final ScrollabilityCache scrollabilityCache = mScrollCache;
10684        scrollabilityCache.fadeScrollBars = fadeScrollbars;
10685        if (fadeScrollbars) {
10686            scrollabilityCache.state = ScrollabilityCache.OFF;
10687        } else {
10688            scrollabilityCache.state = ScrollabilityCache.ON;
10689        }
10690    }
10691
10692    /**
10693     *
10694     * Returns true if scrollbars will fade when this view is not scrolling
10695     *
10696     * @return true if scrollbar fading is enabled
10697     *
10698     * @attr ref android.R.styleable#View_fadeScrollbars
10699     */
10700    public boolean isScrollbarFadingEnabled() {
10701        return mScrollCache != null && mScrollCache.fadeScrollBars;
10702    }
10703
10704    /**
10705     *
10706     * Returns the delay before scrollbars fade.
10707     *
10708     * @return the delay before scrollbars fade
10709     *
10710     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10711     */
10712    public int getScrollBarDefaultDelayBeforeFade() {
10713        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
10714                mScrollCache.scrollBarDefaultDelayBeforeFade;
10715    }
10716
10717    /**
10718     * Define the delay before scrollbars fade.
10719     *
10720     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
10721     *
10722     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
10723     */
10724    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
10725        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
10726    }
10727
10728    /**
10729     *
10730     * Returns the scrollbar fade duration.
10731     *
10732     * @return the scrollbar fade duration
10733     *
10734     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10735     */
10736    public int getScrollBarFadeDuration() {
10737        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
10738                mScrollCache.scrollBarFadeDuration;
10739    }
10740
10741    /**
10742     * Define the scrollbar fade duration.
10743     *
10744     * @param scrollBarFadeDuration - the scrollbar fade duration
10745     *
10746     * @attr ref android.R.styleable#View_scrollbarFadeDuration
10747     */
10748    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
10749        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
10750    }
10751
10752    /**
10753     *
10754     * Returns the scrollbar size.
10755     *
10756     * @return the scrollbar size
10757     *
10758     * @attr ref android.R.styleable#View_scrollbarSize
10759     */
10760    public int getScrollBarSize() {
10761        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
10762                mScrollCache.scrollBarSize;
10763    }
10764
10765    /**
10766     * Define the scrollbar size.
10767     *
10768     * @param scrollBarSize - the scrollbar size
10769     *
10770     * @attr ref android.R.styleable#View_scrollbarSize
10771     */
10772    public void setScrollBarSize(int scrollBarSize) {
10773        getScrollCache().scrollBarSize = scrollBarSize;
10774    }
10775
10776    /**
10777     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
10778     * inset. When inset, they add to the padding of the view. And the scrollbars
10779     * can be drawn inside the padding area or on the edge of the view. For example,
10780     * if a view has a background drawable and you want to draw the scrollbars
10781     * inside the padding specified by the drawable, you can use
10782     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
10783     * appear at the edge of the view, ignoring the padding, then you can use
10784     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
10785     * @param style the style of the scrollbars. Should be one of
10786     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
10787     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
10788     * @see #SCROLLBARS_INSIDE_OVERLAY
10789     * @see #SCROLLBARS_INSIDE_INSET
10790     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10791     * @see #SCROLLBARS_OUTSIDE_INSET
10792     *
10793     * @attr ref android.R.styleable#View_scrollbarStyle
10794     */
10795    public void setScrollBarStyle(int style) {
10796        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
10797            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
10798            computeOpaqueFlags();
10799            resolvePadding();
10800        }
10801    }
10802
10803    /**
10804     * <p>Returns the current scrollbar style.</p>
10805     * @return the current scrollbar style
10806     * @see #SCROLLBARS_INSIDE_OVERLAY
10807     * @see #SCROLLBARS_INSIDE_INSET
10808     * @see #SCROLLBARS_OUTSIDE_OVERLAY
10809     * @see #SCROLLBARS_OUTSIDE_INSET
10810     *
10811     * @attr ref android.R.styleable#View_scrollbarStyle
10812     */
10813    @ViewDebug.ExportedProperty(mapping = {
10814            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
10815            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
10816            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
10817            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
10818    })
10819    public int getScrollBarStyle() {
10820        return mViewFlags & SCROLLBARS_STYLE_MASK;
10821    }
10822
10823    /**
10824     * <p>Compute the horizontal range that the horizontal scrollbar
10825     * represents.</p>
10826     *
10827     * <p>The range is expressed in arbitrary units that must be the same as the
10828     * units used by {@link #computeHorizontalScrollExtent()} and
10829     * {@link #computeHorizontalScrollOffset()}.</p>
10830     *
10831     * <p>The default range is the drawing width of this view.</p>
10832     *
10833     * @return the total horizontal range represented by the horizontal
10834     *         scrollbar
10835     *
10836     * @see #computeHorizontalScrollExtent()
10837     * @see #computeHorizontalScrollOffset()
10838     * @see android.widget.ScrollBarDrawable
10839     */
10840    protected int computeHorizontalScrollRange() {
10841        return getWidth();
10842    }
10843
10844    /**
10845     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
10846     * within the horizontal range. This value is used to compute the position
10847     * of the thumb within the scrollbar's track.</p>
10848     *
10849     * <p>The range is expressed in arbitrary units that must be the same as the
10850     * units used by {@link #computeHorizontalScrollRange()} and
10851     * {@link #computeHorizontalScrollExtent()}.</p>
10852     *
10853     * <p>The default offset is the scroll offset of this view.</p>
10854     *
10855     * @return the horizontal offset of the scrollbar's thumb
10856     *
10857     * @see #computeHorizontalScrollRange()
10858     * @see #computeHorizontalScrollExtent()
10859     * @see android.widget.ScrollBarDrawable
10860     */
10861    protected int computeHorizontalScrollOffset() {
10862        return mScrollX;
10863    }
10864
10865    /**
10866     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
10867     * within the horizontal range. This value is used to compute the length
10868     * of the thumb within the scrollbar's track.</p>
10869     *
10870     * <p>The range is expressed in arbitrary units that must be the same as the
10871     * units used by {@link #computeHorizontalScrollRange()} and
10872     * {@link #computeHorizontalScrollOffset()}.</p>
10873     *
10874     * <p>The default extent is the drawing width of this view.</p>
10875     *
10876     * @return the horizontal extent of the scrollbar's thumb
10877     *
10878     * @see #computeHorizontalScrollRange()
10879     * @see #computeHorizontalScrollOffset()
10880     * @see android.widget.ScrollBarDrawable
10881     */
10882    protected int computeHorizontalScrollExtent() {
10883        return getWidth();
10884    }
10885
10886    /**
10887     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
10888     *
10889     * <p>The range is expressed in arbitrary units that must be the same as the
10890     * units used by {@link #computeVerticalScrollExtent()} and
10891     * {@link #computeVerticalScrollOffset()}.</p>
10892     *
10893     * @return the total vertical range represented by the vertical scrollbar
10894     *
10895     * <p>The default range is the drawing height of this view.</p>
10896     *
10897     * @see #computeVerticalScrollExtent()
10898     * @see #computeVerticalScrollOffset()
10899     * @see android.widget.ScrollBarDrawable
10900     */
10901    protected int computeVerticalScrollRange() {
10902        return getHeight();
10903    }
10904
10905    /**
10906     * <p>Compute the vertical offset of the vertical scrollbar's thumb
10907     * within the horizontal range. This value is used to compute the position
10908     * of the thumb within the scrollbar's track.</p>
10909     *
10910     * <p>The range is expressed in arbitrary units that must be the same as the
10911     * units used by {@link #computeVerticalScrollRange()} and
10912     * {@link #computeVerticalScrollExtent()}.</p>
10913     *
10914     * <p>The default offset is the scroll offset of this view.</p>
10915     *
10916     * @return the vertical offset of the scrollbar's thumb
10917     *
10918     * @see #computeVerticalScrollRange()
10919     * @see #computeVerticalScrollExtent()
10920     * @see android.widget.ScrollBarDrawable
10921     */
10922    protected int computeVerticalScrollOffset() {
10923        return mScrollY;
10924    }
10925
10926    /**
10927     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
10928     * within the vertical range. This value is used to compute the length
10929     * of the thumb within the scrollbar's track.</p>
10930     *
10931     * <p>The range is expressed in arbitrary units that must be the same as the
10932     * units used by {@link #computeVerticalScrollRange()} and
10933     * {@link #computeVerticalScrollOffset()}.</p>
10934     *
10935     * <p>The default extent is the drawing height of this view.</p>
10936     *
10937     * @return the vertical extent of the scrollbar's thumb
10938     *
10939     * @see #computeVerticalScrollRange()
10940     * @see #computeVerticalScrollOffset()
10941     * @see android.widget.ScrollBarDrawable
10942     */
10943    protected int computeVerticalScrollExtent() {
10944        return getHeight();
10945    }
10946
10947    /**
10948     * Check if this view can be scrolled horizontally in a certain direction.
10949     *
10950     * @param direction Negative to check scrolling left, positive to check scrolling right.
10951     * @return true if this view can be scrolled in the specified direction, false otherwise.
10952     */
10953    public boolean canScrollHorizontally(int direction) {
10954        final int offset = computeHorizontalScrollOffset();
10955        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
10956        if (range == 0) return false;
10957        if (direction < 0) {
10958            return offset > 0;
10959        } else {
10960            return offset < range - 1;
10961        }
10962    }
10963
10964    /**
10965     * Check if this view can be scrolled vertically in a certain direction.
10966     *
10967     * @param direction Negative to check scrolling up, positive to check scrolling down.
10968     * @return true if this view can be scrolled in the specified direction, false otherwise.
10969     */
10970    public boolean canScrollVertically(int direction) {
10971        final int offset = computeVerticalScrollOffset();
10972        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
10973        if (range == 0) return false;
10974        if (direction < 0) {
10975            return offset > 0;
10976        } else {
10977            return offset < range - 1;
10978        }
10979    }
10980
10981    /**
10982     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
10983     * scrollbars are painted only if they have been awakened first.</p>
10984     *
10985     * @param canvas the canvas on which to draw the scrollbars
10986     *
10987     * @see #awakenScrollBars(int)
10988     */
10989    protected final void onDrawScrollBars(Canvas canvas) {
10990        // scrollbars are drawn only when the animation is running
10991        final ScrollabilityCache cache = mScrollCache;
10992        if (cache != null) {
10993
10994            int state = cache.state;
10995
10996            if (state == ScrollabilityCache.OFF) {
10997                return;
10998            }
10999
11000            boolean invalidate = false;
11001
11002            if (state == ScrollabilityCache.FADING) {
11003                // We're fading -- get our fade interpolation
11004                if (cache.interpolatorValues == null) {
11005                    cache.interpolatorValues = new float[1];
11006                }
11007
11008                float[] values = cache.interpolatorValues;
11009
11010                // Stops the animation if we're done
11011                if (cache.scrollBarInterpolator.timeToValues(values) ==
11012                        Interpolator.Result.FREEZE_END) {
11013                    cache.state = ScrollabilityCache.OFF;
11014                } else {
11015                    cache.scrollBar.setAlpha(Math.round(values[0]));
11016                }
11017
11018                // This will make the scroll bars inval themselves after
11019                // drawing. We only want this when we're fading so that
11020                // we prevent excessive redraws
11021                invalidate = true;
11022            } else {
11023                // We're just on -- but we may have been fading before so
11024                // reset alpha
11025                cache.scrollBar.setAlpha(255);
11026            }
11027
11028
11029            final int viewFlags = mViewFlags;
11030
11031            final boolean drawHorizontalScrollBar =
11032                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11033            final boolean drawVerticalScrollBar =
11034                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11035                && !isVerticalScrollBarHidden();
11036
11037            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11038                final int width = mRight - mLeft;
11039                final int height = mBottom - mTop;
11040
11041                final ScrollBarDrawable scrollBar = cache.scrollBar;
11042
11043                final int scrollX = mScrollX;
11044                final int scrollY = mScrollY;
11045                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11046
11047                int left, top, right, bottom;
11048
11049                if (drawHorizontalScrollBar) {
11050                    int size = scrollBar.getSize(false);
11051                    if (size <= 0) {
11052                        size = cache.scrollBarSize;
11053                    }
11054
11055                    scrollBar.setParameters(computeHorizontalScrollRange(),
11056                                            computeHorizontalScrollOffset(),
11057                                            computeHorizontalScrollExtent(), false);
11058                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11059                            getVerticalScrollbarWidth() : 0;
11060                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11061                    left = scrollX + (mPaddingLeft & inside);
11062                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11063                    bottom = top + size;
11064                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11065                    if (invalidate) {
11066                        invalidate(left, top, right, bottom);
11067                    }
11068                }
11069
11070                if (drawVerticalScrollBar) {
11071                    int size = scrollBar.getSize(true);
11072                    if (size <= 0) {
11073                        size = cache.scrollBarSize;
11074                    }
11075
11076                    scrollBar.setParameters(computeVerticalScrollRange(),
11077                                            computeVerticalScrollOffset(),
11078                                            computeVerticalScrollExtent(), true);
11079                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11080                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11081                        verticalScrollbarPosition = isLayoutRtl() ?
11082                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11083                    }
11084                    switch (verticalScrollbarPosition) {
11085                        default:
11086                        case SCROLLBAR_POSITION_RIGHT:
11087                            left = scrollX + width - size - (mUserPaddingRight & inside);
11088                            break;
11089                        case SCROLLBAR_POSITION_LEFT:
11090                            left = scrollX + (mUserPaddingLeft & inside);
11091                            break;
11092                    }
11093                    top = scrollY + (mPaddingTop & inside);
11094                    right = left + size;
11095                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11096                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11097                    if (invalidate) {
11098                        invalidate(left, top, right, bottom);
11099                    }
11100                }
11101            }
11102        }
11103    }
11104
11105    /**
11106     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11107     * FastScroller is visible.
11108     * @return whether to temporarily hide the vertical scrollbar
11109     * @hide
11110     */
11111    protected boolean isVerticalScrollBarHidden() {
11112        return false;
11113    }
11114
11115    /**
11116     * <p>Draw the horizontal scrollbar if
11117     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11118     *
11119     * @param canvas the canvas on which to draw the scrollbar
11120     * @param scrollBar the scrollbar's drawable
11121     *
11122     * @see #isHorizontalScrollBarEnabled()
11123     * @see #computeHorizontalScrollRange()
11124     * @see #computeHorizontalScrollExtent()
11125     * @see #computeHorizontalScrollOffset()
11126     * @see android.widget.ScrollBarDrawable
11127     * @hide
11128     */
11129    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11130            int l, int t, int r, int b) {
11131        scrollBar.setBounds(l, t, r, b);
11132        scrollBar.draw(canvas);
11133    }
11134
11135    /**
11136     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11137     * returns true.</p>
11138     *
11139     * @param canvas the canvas on which to draw the scrollbar
11140     * @param scrollBar the scrollbar's drawable
11141     *
11142     * @see #isVerticalScrollBarEnabled()
11143     * @see #computeVerticalScrollRange()
11144     * @see #computeVerticalScrollExtent()
11145     * @see #computeVerticalScrollOffset()
11146     * @see android.widget.ScrollBarDrawable
11147     * @hide
11148     */
11149    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11150            int l, int t, int r, int b) {
11151        scrollBar.setBounds(l, t, r, b);
11152        scrollBar.draw(canvas);
11153    }
11154
11155    /**
11156     * Implement this to do your drawing.
11157     *
11158     * @param canvas the canvas on which the background will be drawn
11159     */
11160    protected void onDraw(Canvas canvas) {
11161    }
11162
11163    /*
11164     * Caller is responsible for calling requestLayout if necessary.
11165     * (This allows addViewInLayout to not request a new layout.)
11166     */
11167    void assignParent(ViewParent parent) {
11168        if (mParent == null) {
11169            mParent = parent;
11170        } else if (parent == null) {
11171            mParent = null;
11172        } else {
11173            throw new RuntimeException("view " + this + " being added, but"
11174                    + " it already has a parent");
11175        }
11176    }
11177
11178    /**
11179     * This is called when the view is attached to a window.  At this point it
11180     * has a Surface and will start drawing.  Note that this function is
11181     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11182     * however it may be called any time before the first onDraw -- including
11183     * before or after {@link #onMeasure(int, int)}.
11184     *
11185     * @see #onDetachedFromWindow()
11186     */
11187    protected void onAttachedToWindow() {
11188        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
11189            mParent.requestTransparentRegion(this);
11190        }
11191
11192        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11193            initialAwakenScrollBars();
11194            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
11195        }
11196
11197        jumpDrawablesToCurrentState();
11198
11199        // Order is important here: LayoutDirection MUST be resolved before Padding
11200        // and TextDirection
11201        resolveLayoutDirection();
11202        resolvePadding();
11203        resolveTextDirection();
11204        resolveTextAlignment();
11205
11206        clearAccessibilityFocus();
11207        if (isFocused()) {
11208            InputMethodManager imm = InputMethodManager.peekInstance();
11209            imm.focusIn(this);
11210        }
11211
11212        if (mAttachInfo != null && mDisplayList != null) {
11213            mAttachInfo.mViewRootImpl.dequeueDisplayList(mDisplayList);
11214        }
11215    }
11216
11217    /**
11218     * @see #onScreenStateChanged(int)
11219     */
11220    void dispatchScreenStateChanged(int screenState) {
11221        onScreenStateChanged(screenState);
11222    }
11223
11224    /**
11225     * This method is called whenever the state of the screen this view is
11226     * attached to changes. A state change will usually occurs when the screen
11227     * turns on or off (whether it happens automatically or the user does it
11228     * manually.)
11229     *
11230     * @param screenState The new state of the screen. Can be either
11231     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11232     */
11233    public void onScreenStateChanged(int screenState) {
11234    }
11235
11236    /**
11237     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11238     */
11239    private boolean hasRtlSupport() {
11240        return mContext.getApplicationInfo().hasRtlSupport();
11241    }
11242
11243    /**
11244     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11245     * that the parent directionality can and will be resolved before its children.
11246     * Will call {@link View#onResolvedLayoutDirectionChanged} when resolution is done.
11247     */
11248    public void resolveLayoutDirection() {
11249        // Clear any previous layout direction resolution
11250        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11251
11252        if (hasRtlSupport()) {
11253            // Set resolved depending on layout direction
11254            switch (getLayoutDirection()) {
11255                case LAYOUT_DIRECTION_INHERIT:
11256                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11257                    // later to get the correct resolved value
11258                    if (!canResolveLayoutDirection()) return;
11259
11260                    ViewGroup viewGroup = ((ViewGroup) mParent);
11261
11262                    // We cannot resolve yet on the parent too. LTR is by default and let the
11263                    // resolution happen again later
11264                    if (!viewGroup.canResolveLayoutDirection()) return;
11265
11266                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11267                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11268                    }
11269                    break;
11270                case LAYOUT_DIRECTION_RTL:
11271                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11272                    break;
11273                case LAYOUT_DIRECTION_LOCALE:
11274                    if(isLayoutDirectionRtl(Locale.getDefault())) {
11275                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
11276                    }
11277                    break;
11278                default:
11279                    // Nothing to do, LTR by default
11280            }
11281        }
11282
11283        // Set to resolved
11284        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
11285        onResolvedLayoutDirectionChanged();
11286        // Resolve padding
11287        resolvePadding();
11288    }
11289
11290    /**
11291     * Called when layout direction has been resolved.
11292     *
11293     * The default implementation does nothing.
11294     */
11295    public void onResolvedLayoutDirectionChanged() {
11296    }
11297
11298    /**
11299     * Resolve padding depending on layout direction.
11300     */
11301    public void resolvePadding() {
11302        // If the user specified the absolute padding (either with android:padding or
11303        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
11304        // use the default padding or the padding from the background drawable
11305        // (stored at this point in mPadding*)
11306        int resolvedLayoutDirection = getResolvedLayoutDirection();
11307        switch (resolvedLayoutDirection) {
11308            case LAYOUT_DIRECTION_RTL:
11309                // Start user padding override Right user padding. Otherwise, if Right user
11310                // padding is not defined, use the default Right padding. If Right user padding
11311                // is defined, just use it.
11312                if (mUserPaddingStart >= 0) {
11313                    mUserPaddingRight = mUserPaddingStart;
11314                } else if (mUserPaddingRight < 0) {
11315                    mUserPaddingRight = mPaddingRight;
11316                }
11317                if (mUserPaddingEnd >= 0) {
11318                    mUserPaddingLeft = mUserPaddingEnd;
11319                } else if (mUserPaddingLeft < 0) {
11320                    mUserPaddingLeft = mPaddingLeft;
11321                }
11322                break;
11323            case LAYOUT_DIRECTION_LTR:
11324            default:
11325                // Start user padding override Left user padding. Otherwise, if Left user
11326                // padding is not defined, use the default left padding. If Left user padding
11327                // is defined, just use it.
11328                if (mUserPaddingStart >= 0) {
11329                    mUserPaddingLeft = mUserPaddingStart;
11330                } else if (mUserPaddingLeft < 0) {
11331                    mUserPaddingLeft = mPaddingLeft;
11332                }
11333                if (mUserPaddingEnd >= 0) {
11334                    mUserPaddingRight = mUserPaddingEnd;
11335                } else if (mUserPaddingRight < 0) {
11336                    mUserPaddingRight = mPaddingRight;
11337                }
11338        }
11339
11340        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11341
11342        if(isPaddingRelative()) {
11343            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
11344        } else {
11345            recomputePadding();
11346        }
11347        onPaddingChanged(resolvedLayoutDirection);
11348    }
11349
11350    /**
11351     * Resolve padding depending on the layout direction. Subclasses that care about
11352     * padding resolution should override this method. The default implementation does
11353     * nothing.
11354     *
11355     * @param layoutDirection the direction of the layout
11356     *
11357     * @see {@link #LAYOUT_DIRECTION_LTR}
11358     * @see {@link #LAYOUT_DIRECTION_RTL}
11359     */
11360    public void onPaddingChanged(int layoutDirection) {
11361    }
11362
11363    /**
11364     * Check if layout direction resolution can be done.
11365     *
11366     * @return true if layout direction resolution can be done otherwise return false.
11367     */
11368    public boolean canResolveLayoutDirection() {
11369        switch (getLayoutDirection()) {
11370            case LAYOUT_DIRECTION_INHERIT:
11371                return (mParent != null) && (mParent instanceof ViewGroup);
11372            default:
11373                return true;
11374        }
11375    }
11376
11377    /**
11378     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
11379     * when reset is done.
11380     */
11381    public void resetResolvedLayoutDirection() {
11382        // Reset the current resolved bits
11383        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_MASK;
11384        onResolvedLayoutDirectionReset();
11385        // Reset also the text direction
11386        resetResolvedTextDirection();
11387    }
11388
11389    /**
11390     * Called during reset of resolved layout direction.
11391     *
11392     * Subclasses need to override this method to clear cached information that depends on the
11393     * resolved layout direction, or to inform child views that inherit their layout direction.
11394     *
11395     * The default implementation does nothing.
11396     */
11397    public void onResolvedLayoutDirectionReset() {
11398    }
11399
11400    /**
11401     * Check if a Locale uses an RTL script.
11402     *
11403     * @param locale Locale to check
11404     * @return true if the Locale uses an RTL script.
11405     */
11406    protected static boolean isLayoutDirectionRtl(Locale locale) {
11407        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
11408    }
11409
11410    /**
11411     * This is called when the view is detached from a window.  At this point it
11412     * no longer has a surface for drawing.
11413     *
11414     * @see #onAttachedToWindow()
11415     */
11416    protected void onDetachedFromWindow() {
11417        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
11418
11419        removeUnsetPressCallback();
11420        removeLongPressCallback();
11421        removePerformClickCallback();
11422        removeSendViewScrolledAccessibilityEventCallback();
11423
11424        destroyDrawingCache();
11425
11426        destroyLayer(false);
11427
11428        if (mAttachInfo != null) {
11429            if (mDisplayList != null) {
11430                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11431            }
11432            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11433        } else {
11434            // Should never happen
11435            clearDisplayList();
11436        }
11437
11438        mCurrentAnimation = null;
11439
11440        resetResolvedLayoutDirection();
11441        resetResolvedTextAlignment();
11442        resetAccessibilityStateChanged();
11443    }
11444
11445    /**
11446     * @return The number of times this view has been attached to a window
11447     */
11448    protected int getWindowAttachCount() {
11449        return mWindowAttachCount;
11450    }
11451
11452    /**
11453     * Retrieve a unique token identifying the window this view is attached to.
11454     * @return Return the window's token for use in
11455     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
11456     */
11457    public IBinder getWindowToken() {
11458        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
11459    }
11460
11461    /**
11462     * Retrieve a unique token identifying the top-level "real" window of
11463     * the window that this view is attached to.  That is, this is like
11464     * {@link #getWindowToken}, except if the window this view in is a panel
11465     * window (attached to another containing window), then the token of
11466     * the containing window is returned instead.
11467     *
11468     * @return Returns the associated window token, either
11469     * {@link #getWindowToken()} or the containing window's token.
11470     */
11471    public IBinder getApplicationWindowToken() {
11472        AttachInfo ai = mAttachInfo;
11473        if (ai != null) {
11474            IBinder appWindowToken = ai.mPanelParentWindowToken;
11475            if (appWindowToken == null) {
11476                appWindowToken = ai.mWindowToken;
11477            }
11478            return appWindowToken;
11479        }
11480        return null;
11481    }
11482
11483    /**
11484     * Retrieve private session object this view hierarchy is using to
11485     * communicate with the window manager.
11486     * @return the session object to communicate with the window manager
11487     */
11488    /*package*/ IWindowSession getWindowSession() {
11489        return mAttachInfo != null ? mAttachInfo.mSession : null;
11490    }
11491
11492    /**
11493     * @param info the {@link android.view.View.AttachInfo} to associated with
11494     *        this view
11495     */
11496    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
11497        //System.out.println("Attached! " + this);
11498        mAttachInfo = info;
11499        mWindowAttachCount++;
11500        // We will need to evaluate the drawable state at least once.
11501        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11502        if (mFloatingTreeObserver != null) {
11503            info.mTreeObserver.merge(mFloatingTreeObserver);
11504            mFloatingTreeObserver = null;
11505        }
11506        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
11507            mAttachInfo.mScrollContainers.add(this);
11508            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
11509        }
11510        performCollectViewAttributes(mAttachInfo, visibility);
11511        onAttachedToWindow();
11512
11513        ListenerInfo li = mListenerInfo;
11514        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11515                li != null ? li.mOnAttachStateChangeListeners : null;
11516        if (listeners != null && listeners.size() > 0) {
11517            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11518            // perform the dispatching. The iterator is a safe guard against listeners that
11519            // could mutate the list by calling the various add/remove methods. This prevents
11520            // the array from being modified while we iterate it.
11521            for (OnAttachStateChangeListener listener : listeners) {
11522                listener.onViewAttachedToWindow(this);
11523            }
11524        }
11525
11526        int vis = info.mWindowVisibility;
11527        if (vis != GONE) {
11528            onWindowVisibilityChanged(vis);
11529        }
11530        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
11531            // If nobody has evaluated the drawable state yet, then do it now.
11532            refreshDrawableState();
11533        }
11534    }
11535
11536    void dispatchDetachedFromWindow() {
11537        AttachInfo info = mAttachInfo;
11538        if (info != null) {
11539            int vis = info.mWindowVisibility;
11540            if (vis != GONE) {
11541                onWindowVisibilityChanged(GONE);
11542            }
11543        }
11544
11545        onDetachedFromWindow();
11546
11547        ListenerInfo li = mListenerInfo;
11548        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
11549                li != null ? li.mOnAttachStateChangeListeners : null;
11550        if (listeners != null && listeners.size() > 0) {
11551            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
11552            // perform the dispatching. The iterator is a safe guard against listeners that
11553            // could mutate the list by calling the various add/remove methods. This prevents
11554            // the array from being modified while we iterate it.
11555            for (OnAttachStateChangeListener listener : listeners) {
11556                listener.onViewDetachedFromWindow(this);
11557            }
11558        }
11559
11560        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
11561            mAttachInfo.mScrollContainers.remove(this);
11562            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
11563        }
11564
11565        mAttachInfo = null;
11566    }
11567
11568    /**
11569     * Store this view hierarchy's frozen state into the given container.
11570     *
11571     * @param container The SparseArray in which to save the view's state.
11572     *
11573     * @see #restoreHierarchyState(android.util.SparseArray)
11574     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11575     * @see #onSaveInstanceState()
11576     */
11577    public void saveHierarchyState(SparseArray<Parcelable> container) {
11578        dispatchSaveInstanceState(container);
11579    }
11580
11581    /**
11582     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
11583     * this view and its children. May be overridden to modify how freezing happens to a
11584     * view's children; for example, some views may want to not store state for their children.
11585     *
11586     * @param container The SparseArray in which to save the view's state.
11587     *
11588     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11589     * @see #saveHierarchyState(android.util.SparseArray)
11590     * @see #onSaveInstanceState()
11591     */
11592    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
11593        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
11594            mPrivateFlags &= ~SAVE_STATE_CALLED;
11595            Parcelable state = onSaveInstanceState();
11596            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11597                throw new IllegalStateException(
11598                        "Derived class did not call super.onSaveInstanceState()");
11599            }
11600            if (state != null) {
11601                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
11602                // + ": " + state);
11603                container.put(mID, state);
11604            }
11605        }
11606    }
11607
11608    /**
11609     * Hook allowing a view to generate a representation of its internal state
11610     * that can later be used to create a new instance with that same state.
11611     * This state should only contain information that is not persistent or can
11612     * not be reconstructed later. For example, you will never store your
11613     * current position on screen because that will be computed again when a
11614     * new instance of the view is placed in its view hierarchy.
11615     * <p>
11616     * Some examples of things you may store here: the current cursor position
11617     * in a text view (but usually not the text itself since that is stored in a
11618     * content provider or other persistent storage), the currently selected
11619     * item in a list view.
11620     *
11621     * @return Returns a Parcelable object containing the view's current dynamic
11622     *         state, or null if there is nothing interesting to save. The
11623     *         default implementation returns null.
11624     * @see #onRestoreInstanceState(android.os.Parcelable)
11625     * @see #saveHierarchyState(android.util.SparseArray)
11626     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11627     * @see #setSaveEnabled(boolean)
11628     */
11629    protected Parcelable onSaveInstanceState() {
11630        mPrivateFlags |= SAVE_STATE_CALLED;
11631        return BaseSavedState.EMPTY_STATE;
11632    }
11633
11634    /**
11635     * Restore this view hierarchy's frozen state from the given container.
11636     *
11637     * @param container The SparseArray which holds previously frozen states.
11638     *
11639     * @see #saveHierarchyState(android.util.SparseArray)
11640     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11641     * @see #onRestoreInstanceState(android.os.Parcelable)
11642     */
11643    public void restoreHierarchyState(SparseArray<Parcelable> container) {
11644        dispatchRestoreInstanceState(container);
11645    }
11646
11647    /**
11648     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
11649     * state for this view and its children. May be overridden to modify how restoring
11650     * happens to a view's children; for example, some views may want to not store state
11651     * for their children.
11652     *
11653     * @param container The SparseArray which holds previously saved state.
11654     *
11655     * @see #dispatchSaveInstanceState(android.util.SparseArray)
11656     * @see #restoreHierarchyState(android.util.SparseArray)
11657     * @see #onRestoreInstanceState(android.os.Parcelable)
11658     */
11659    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
11660        if (mID != NO_ID) {
11661            Parcelable state = container.get(mID);
11662            if (state != null) {
11663                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
11664                // + ": " + state);
11665                mPrivateFlags &= ~SAVE_STATE_CALLED;
11666                onRestoreInstanceState(state);
11667                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
11668                    throw new IllegalStateException(
11669                            "Derived class did not call super.onRestoreInstanceState()");
11670                }
11671            }
11672        }
11673    }
11674
11675    /**
11676     * Hook allowing a view to re-apply a representation of its internal state that had previously
11677     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
11678     * null state.
11679     *
11680     * @param state The frozen state that had previously been returned by
11681     *        {@link #onSaveInstanceState}.
11682     *
11683     * @see #onSaveInstanceState()
11684     * @see #restoreHierarchyState(android.util.SparseArray)
11685     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
11686     */
11687    protected void onRestoreInstanceState(Parcelable state) {
11688        mPrivateFlags |= SAVE_STATE_CALLED;
11689        if (state != BaseSavedState.EMPTY_STATE && state != null) {
11690            throw new IllegalArgumentException("Wrong state class, expecting View State but "
11691                    + "received " + state.getClass().toString() + " instead. This usually happens "
11692                    + "when two views of different type have the same id in the same hierarchy. "
11693                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
11694                    + "other views do not use the same id.");
11695        }
11696    }
11697
11698    /**
11699     * <p>Return the time at which the drawing of the view hierarchy started.</p>
11700     *
11701     * @return the drawing start time in milliseconds
11702     */
11703    public long getDrawingTime() {
11704        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
11705    }
11706
11707    /**
11708     * <p>Enables or disables the duplication of the parent's state into this view. When
11709     * duplication is enabled, this view gets its drawable state from its parent rather
11710     * than from its own internal properties.</p>
11711     *
11712     * <p>Note: in the current implementation, setting this property to true after the
11713     * view was added to a ViewGroup might have no effect at all. This property should
11714     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
11715     *
11716     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
11717     * property is enabled, an exception will be thrown.</p>
11718     *
11719     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
11720     * parent, these states should not be affected by this method.</p>
11721     *
11722     * @param enabled True to enable duplication of the parent's drawable state, false
11723     *                to disable it.
11724     *
11725     * @see #getDrawableState()
11726     * @see #isDuplicateParentStateEnabled()
11727     */
11728    public void setDuplicateParentStateEnabled(boolean enabled) {
11729        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
11730    }
11731
11732    /**
11733     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
11734     *
11735     * @return True if this view's drawable state is duplicated from the parent,
11736     *         false otherwise
11737     *
11738     * @see #getDrawableState()
11739     * @see #setDuplicateParentStateEnabled(boolean)
11740     */
11741    public boolean isDuplicateParentStateEnabled() {
11742        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
11743    }
11744
11745    /**
11746     * <p>Specifies the type of layer backing this view. The layer can be
11747     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
11748     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
11749     *
11750     * <p>A layer is associated with an optional {@link android.graphics.Paint}
11751     * instance that controls how the layer is composed on screen. The following
11752     * properties of the paint are taken into account when composing the layer:</p>
11753     * <ul>
11754     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
11755     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
11756     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
11757     * </ul>
11758     *
11759     * <p>If this view has an alpha value set to < 1.0 by calling
11760     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
11761     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
11762     * equivalent to setting a hardware layer on this view and providing a paint with
11763     * the desired alpha value.<p>
11764     *
11765     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
11766     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
11767     * for more information on when and how to use layers.</p>
11768     *
11769     * @param layerType The ype of layer to use with this view, must be one of
11770     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11771     *        {@link #LAYER_TYPE_HARDWARE}
11772     * @param paint The paint used to compose the layer. This argument is optional
11773     *        and can be null. It is ignored when the layer type is
11774     *        {@link #LAYER_TYPE_NONE}
11775     *
11776     * @see #getLayerType()
11777     * @see #LAYER_TYPE_NONE
11778     * @see #LAYER_TYPE_SOFTWARE
11779     * @see #LAYER_TYPE_HARDWARE
11780     * @see #setAlpha(float)
11781     *
11782     * @attr ref android.R.styleable#View_layerType
11783     */
11784    public void setLayerType(int layerType, Paint paint) {
11785        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
11786            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
11787                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
11788        }
11789
11790        if (layerType == mLayerType) {
11791            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
11792                mLayerPaint = paint == null ? new Paint() : paint;
11793                invalidateParentCaches();
11794                invalidate(true);
11795            }
11796            return;
11797        }
11798
11799        // Destroy any previous software drawing cache if needed
11800        switch (mLayerType) {
11801            case LAYER_TYPE_HARDWARE:
11802                destroyLayer(false);
11803                // fall through - non-accelerated views may use software layer mechanism instead
11804            case LAYER_TYPE_SOFTWARE:
11805                destroyDrawingCache();
11806                break;
11807            default:
11808                break;
11809        }
11810
11811        mLayerType = layerType;
11812        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
11813        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
11814        mLocalDirtyRect = layerDisabled ? null : new Rect();
11815
11816        invalidateParentCaches();
11817        invalidate(true);
11818    }
11819
11820    /**
11821     * Indicates whether this view has a static layer. A view with layer type
11822     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
11823     * dynamic.
11824     */
11825    boolean hasStaticLayer() {
11826        return true;
11827    }
11828
11829    /**
11830     * Indicates what type of layer is currently associated with this view. By default
11831     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
11832     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
11833     * for more information on the different types of layers.
11834     *
11835     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
11836     *         {@link #LAYER_TYPE_HARDWARE}
11837     *
11838     * @see #setLayerType(int, android.graphics.Paint)
11839     * @see #buildLayer()
11840     * @see #LAYER_TYPE_NONE
11841     * @see #LAYER_TYPE_SOFTWARE
11842     * @see #LAYER_TYPE_HARDWARE
11843     */
11844    public int getLayerType() {
11845        return mLayerType;
11846    }
11847
11848    /**
11849     * Forces this view's layer to be created and this view to be rendered
11850     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
11851     * invoking this method will have no effect.
11852     *
11853     * This method can for instance be used to render a view into its layer before
11854     * starting an animation. If this view is complex, rendering into the layer
11855     * before starting the animation will avoid skipping frames.
11856     *
11857     * @throws IllegalStateException If this view is not attached to a window
11858     *
11859     * @see #setLayerType(int, android.graphics.Paint)
11860     */
11861    public void buildLayer() {
11862        if (mLayerType == LAYER_TYPE_NONE) return;
11863
11864        if (mAttachInfo == null) {
11865            throw new IllegalStateException("This view must be attached to a window first");
11866        }
11867
11868        switch (mLayerType) {
11869            case LAYER_TYPE_HARDWARE:
11870                if (mAttachInfo.mHardwareRenderer != null &&
11871                        mAttachInfo.mHardwareRenderer.isEnabled() &&
11872                        mAttachInfo.mHardwareRenderer.validate()) {
11873                    getHardwareLayer();
11874                }
11875                break;
11876            case LAYER_TYPE_SOFTWARE:
11877                buildDrawingCache(true);
11878                break;
11879        }
11880    }
11881
11882    /**
11883     * <p>Returns a hardware layer that can be used to draw this view again
11884     * without executing its draw method.</p>
11885     *
11886     * @return A HardwareLayer ready to render, or null if an error occurred.
11887     */
11888    HardwareLayer getHardwareLayer() {
11889        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
11890                !mAttachInfo.mHardwareRenderer.isEnabled()) {
11891            return null;
11892        }
11893
11894        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
11895
11896        final int width = mRight - mLeft;
11897        final int height = mBottom - mTop;
11898
11899        if (width == 0 || height == 0) {
11900            return null;
11901        }
11902
11903        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
11904            if (mHardwareLayer == null) {
11905                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
11906                        width, height, isOpaque());
11907                mLocalDirtyRect.set(0, 0, width, height);
11908            } else {
11909                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
11910                    mHardwareLayer.resize(width, height);
11911                    mLocalDirtyRect.set(0, 0, width, height);
11912                }
11913
11914                // This should not be necessary but applications that change
11915                // the parameters of their background drawable without calling
11916                // this.setBackground(Drawable) can leave the view in a bad state
11917                // (for instance isOpaque() returns true, but the background is
11918                // not opaque.)
11919                computeOpaqueFlags();
11920
11921                final boolean opaque = isOpaque();
11922                if (mHardwareLayer.isOpaque() != opaque) {
11923                    mHardwareLayer.setOpaque(opaque);
11924                    mLocalDirtyRect.set(0, 0, width, height);
11925                }
11926            }
11927
11928            // The layer is not valid if the underlying GPU resources cannot be allocated
11929            if (!mHardwareLayer.isValid()) {
11930                return null;
11931            }
11932
11933            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
11934            mLocalDirtyRect.setEmpty();
11935        }
11936
11937        return mHardwareLayer;
11938    }
11939
11940    /**
11941     * Destroys this View's hardware layer if possible.
11942     *
11943     * @return True if the layer was destroyed, false otherwise.
11944     *
11945     * @see #setLayerType(int, android.graphics.Paint)
11946     * @see #LAYER_TYPE_HARDWARE
11947     */
11948    boolean destroyLayer(boolean valid) {
11949        if (mHardwareLayer != null) {
11950            AttachInfo info = mAttachInfo;
11951            if (info != null && info.mHardwareRenderer != null &&
11952                    info.mHardwareRenderer.isEnabled() &&
11953                    (valid || info.mHardwareRenderer.validate())) {
11954                mHardwareLayer.destroy();
11955                mHardwareLayer = null;
11956
11957                invalidate(true);
11958                invalidateParentCaches();
11959            }
11960            return true;
11961        }
11962        return false;
11963    }
11964
11965    /**
11966     * Destroys all hardware rendering resources. This method is invoked
11967     * when the system needs to reclaim resources. Upon execution of this
11968     * method, you should free any OpenGL resources created by the view.
11969     *
11970     * Note: you <strong>must</strong> call
11971     * <code>super.destroyHardwareResources()</code> when overriding
11972     * this method.
11973     *
11974     * @hide
11975     */
11976    protected void destroyHardwareResources() {
11977        destroyLayer(true);
11978    }
11979
11980    /**
11981     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
11982     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
11983     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
11984     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
11985     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
11986     * null.</p>
11987     *
11988     * <p>Enabling the drawing cache is similar to
11989     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
11990     * acceleration is turned off. When hardware acceleration is turned on, enabling the
11991     * drawing cache has no effect on rendering because the system uses a different mechanism
11992     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
11993     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
11994     * for information on how to enable software and hardware layers.</p>
11995     *
11996     * <p>This API can be used to manually generate
11997     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
11998     * {@link #getDrawingCache()}.</p>
11999     *
12000     * @param enabled true to enable the drawing cache, false otherwise
12001     *
12002     * @see #isDrawingCacheEnabled()
12003     * @see #getDrawingCache()
12004     * @see #buildDrawingCache()
12005     * @see #setLayerType(int, android.graphics.Paint)
12006     */
12007    public void setDrawingCacheEnabled(boolean enabled) {
12008        mCachingFailed = false;
12009        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12010    }
12011
12012    /**
12013     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12014     *
12015     * @return true if the drawing cache is enabled
12016     *
12017     * @see #setDrawingCacheEnabled(boolean)
12018     * @see #getDrawingCache()
12019     */
12020    @ViewDebug.ExportedProperty(category = "drawing")
12021    public boolean isDrawingCacheEnabled() {
12022        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12023    }
12024
12025    /**
12026     * Debugging utility which recursively outputs the dirty state of a view and its
12027     * descendants.
12028     *
12029     * @hide
12030     */
12031    @SuppressWarnings({"UnusedDeclaration"})
12032    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12033        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
12034                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
12035                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
12036                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
12037        if (clear) {
12038            mPrivateFlags &= clearMask;
12039        }
12040        if (this instanceof ViewGroup) {
12041            ViewGroup parent = (ViewGroup) this;
12042            final int count = parent.getChildCount();
12043            for (int i = 0; i < count; i++) {
12044                final View child = parent.getChildAt(i);
12045                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12046            }
12047        }
12048    }
12049
12050    /**
12051     * This method is used by ViewGroup to cause its children to restore or recreate their
12052     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12053     * to recreate its own display list, which would happen if it went through the normal
12054     * draw/dispatchDraw mechanisms.
12055     *
12056     * @hide
12057     */
12058    protected void dispatchGetDisplayList() {}
12059
12060    /**
12061     * A view that is not attached or hardware accelerated cannot create a display list.
12062     * This method checks these conditions and returns the appropriate result.
12063     *
12064     * @return true if view has the ability to create a display list, false otherwise.
12065     *
12066     * @hide
12067     */
12068    public boolean canHaveDisplayList() {
12069        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12070    }
12071
12072    /**
12073     * @return The HardwareRenderer associated with that view or null if hardware rendering
12074     * is not supported or this this has not been attached to a window.
12075     *
12076     * @hide
12077     */
12078    public HardwareRenderer getHardwareRenderer() {
12079        if (mAttachInfo != null) {
12080            return mAttachInfo.mHardwareRenderer;
12081        }
12082        return null;
12083    }
12084
12085    /**
12086     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12087     * Otherwise, the same display list will be returned (after having been rendered into
12088     * along the way, depending on the invalidation state of the view).
12089     *
12090     * @param displayList The previous version of this displayList, could be null.
12091     * @param isLayer Whether the requester of the display list is a layer. If so,
12092     * the view will avoid creating a layer inside the resulting display list.
12093     * @return A new or reused DisplayList object.
12094     */
12095    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12096        if (!canHaveDisplayList()) {
12097            return null;
12098        }
12099
12100        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
12101                displayList == null || !displayList.isValid() ||
12102                (!isLayer && mRecreateDisplayList))) {
12103            // Don't need to recreate the display list, just need to tell our
12104            // children to restore/recreate theirs
12105            if (displayList != null && displayList.isValid() &&
12106                    !isLayer && !mRecreateDisplayList) {
12107                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12108                mPrivateFlags &= ~DIRTY_MASK;
12109                dispatchGetDisplayList();
12110
12111                return displayList;
12112            }
12113
12114            if (!isLayer) {
12115                // If we got here, we're recreating it. Mark it as such to ensure that
12116                // we copy in child display lists into ours in drawChild()
12117                mRecreateDisplayList = true;
12118            }
12119            if (displayList == null) {
12120                final String name = getClass().getSimpleName();
12121                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12122                // If we're creating a new display list, make sure our parent gets invalidated
12123                // since they will need to recreate their display list to account for this
12124                // new child display list.
12125                invalidateParentCaches();
12126            }
12127
12128            boolean caching = false;
12129            final HardwareCanvas canvas = displayList.start();
12130            int width = mRight - mLeft;
12131            int height = mBottom - mTop;
12132
12133            try {
12134                canvas.setViewport(width, height);
12135                // The dirty rect should always be null for a display list
12136                canvas.onPreDraw(null);
12137                int layerType = getLayerType();
12138                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12139                    if (layerType == LAYER_TYPE_HARDWARE) {
12140                        final HardwareLayer layer = getHardwareLayer();
12141                        if (layer != null && layer.isValid()) {
12142                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12143                        } else {
12144                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12145                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12146                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12147                        }
12148                        caching = true;
12149                    } else {
12150                        buildDrawingCache(true);
12151                        Bitmap cache = getDrawingCache(true);
12152                        if (cache != null) {
12153                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12154                            caching = true;
12155                        }
12156                    }
12157                } else {
12158
12159                    computeScroll();
12160
12161                    canvas.translate(-mScrollX, -mScrollY);
12162                    if (!isLayer) {
12163                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12164                        mPrivateFlags &= ~DIRTY_MASK;
12165                    }
12166
12167                    // Fast path for layouts with no backgrounds
12168                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12169                        dispatchDraw(canvas);
12170                    } else {
12171                        draw(canvas);
12172                    }
12173                }
12174            } finally {
12175                canvas.onPostDraw();
12176
12177                displayList.end();
12178                displayList.setCaching(caching);
12179                if (isLayer) {
12180                    displayList.setLeftTopRightBottom(0, 0, width, height);
12181                } else {
12182                    setDisplayListProperties(displayList);
12183                }
12184            }
12185        } else if (!isLayer) {
12186            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
12187            mPrivateFlags &= ~DIRTY_MASK;
12188        }
12189
12190        return displayList;
12191    }
12192
12193    /**
12194     * Get the DisplayList for the HardwareLayer
12195     *
12196     * @param layer The HardwareLayer whose DisplayList we want
12197     * @return A DisplayList fopr the specified HardwareLayer
12198     */
12199    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12200        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12201        layer.setDisplayList(displayList);
12202        return displayList;
12203    }
12204
12205
12206    /**
12207     * <p>Returns a display list that can be used to draw this view again
12208     * without executing its draw method.</p>
12209     *
12210     * @return A DisplayList ready to replay, or null if caching is not enabled.
12211     *
12212     * @hide
12213     */
12214    public DisplayList getDisplayList() {
12215        mDisplayList = getDisplayList(mDisplayList, false);
12216        return mDisplayList;
12217    }
12218
12219    private void clearDisplayList() {
12220        if (mDisplayList != null) {
12221            mDisplayList.invalidate();
12222            mDisplayList.clear();
12223        }
12224    }
12225
12226    /**
12227     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12228     *
12229     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12230     *
12231     * @see #getDrawingCache(boolean)
12232     */
12233    public Bitmap getDrawingCache() {
12234        return getDrawingCache(false);
12235    }
12236
12237    /**
12238     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12239     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12240     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12241     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12242     * request the drawing cache by calling this method and draw it on screen if the
12243     * returned bitmap is not null.</p>
12244     *
12245     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12246     * this method will create a bitmap of the same size as this view. Because this bitmap
12247     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12248     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12249     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12250     * size than the view. This implies that your application must be able to handle this
12251     * size.</p>
12252     *
12253     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12254     *        the current density of the screen when the application is in compatibility
12255     *        mode.
12256     *
12257     * @return A bitmap representing this view or null if cache is disabled.
12258     *
12259     * @see #setDrawingCacheEnabled(boolean)
12260     * @see #isDrawingCacheEnabled()
12261     * @see #buildDrawingCache(boolean)
12262     * @see #destroyDrawingCache()
12263     */
12264    public Bitmap getDrawingCache(boolean autoScale) {
12265        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12266            return null;
12267        }
12268        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12269            buildDrawingCache(autoScale);
12270        }
12271        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12272    }
12273
12274    /**
12275     * <p>Frees the resources used by the drawing cache. If you call
12276     * {@link #buildDrawingCache()} manually without calling
12277     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12278     * should cleanup the cache with this method afterwards.</p>
12279     *
12280     * @see #setDrawingCacheEnabled(boolean)
12281     * @see #buildDrawingCache()
12282     * @see #getDrawingCache()
12283     */
12284    public void destroyDrawingCache() {
12285        if (mDrawingCache != null) {
12286            mDrawingCache.recycle();
12287            mDrawingCache = null;
12288        }
12289        if (mUnscaledDrawingCache != null) {
12290            mUnscaledDrawingCache.recycle();
12291            mUnscaledDrawingCache = null;
12292        }
12293    }
12294
12295    /**
12296     * Setting a solid background color for the drawing cache's bitmaps will improve
12297     * performance and memory usage. Note, though that this should only be used if this
12298     * view will always be drawn on top of a solid color.
12299     *
12300     * @param color The background color to use for the drawing cache's bitmap
12301     *
12302     * @see #setDrawingCacheEnabled(boolean)
12303     * @see #buildDrawingCache()
12304     * @see #getDrawingCache()
12305     */
12306    public void setDrawingCacheBackgroundColor(int color) {
12307        if (color != mDrawingCacheBackgroundColor) {
12308            mDrawingCacheBackgroundColor = color;
12309            mPrivateFlags &= ~DRAWING_CACHE_VALID;
12310        }
12311    }
12312
12313    /**
12314     * @see #setDrawingCacheBackgroundColor(int)
12315     *
12316     * @return The background color to used for the drawing cache's bitmap
12317     */
12318    public int getDrawingCacheBackgroundColor() {
12319        return mDrawingCacheBackgroundColor;
12320    }
12321
12322    /**
12323     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12324     *
12325     * @see #buildDrawingCache(boolean)
12326     */
12327    public void buildDrawingCache() {
12328        buildDrawingCache(false);
12329    }
12330
12331    /**
12332     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12333     *
12334     * <p>If you call {@link #buildDrawingCache()} manually without calling
12335     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12336     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12337     *
12338     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12339     * this method will create a bitmap of the same size as this view. Because this bitmap
12340     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12341     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12342     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12343     * size than the view. This implies that your application must be able to handle this
12344     * size.</p>
12345     *
12346     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12347     * you do not need the drawing cache bitmap, calling this method will increase memory
12348     * usage and cause the view to be rendered in software once, thus negatively impacting
12349     * performance.</p>
12350     *
12351     * @see #getDrawingCache()
12352     * @see #destroyDrawingCache()
12353     */
12354    public void buildDrawingCache(boolean autoScale) {
12355        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
12356                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12357            mCachingFailed = false;
12358
12359            int width = mRight - mLeft;
12360            int height = mBottom - mTop;
12361
12362            final AttachInfo attachInfo = mAttachInfo;
12363            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
12364
12365            if (autoScale && scalingRequired) {
12366                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
12367                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
12368            }
12369
12370            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
12371            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
12372            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
12373
12374            if (width <= 0 || height <= 0 ||
12375                     // Projected bitmap size in bytes
12376                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
12377                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
12378                destroyDrawingCache();
12379                mCachingFailed = true;
12380                return;
12381            }
12382
12383            boolean clear = true;
12384            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
12385
12386            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
12387                Bitmap.Config quality;
12388                if (!opaque) {
12389                    // Never pick ARGB_4444 because it looks awful
12390                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
12391                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
12392                        case DRAWING_CACHE_QUALITY_AUTO:
12393                            quality = Bitmap.Config.ARGB_8888;
12394                            break;
12395                        case DRAWING_CACHE_QUALITY_LOW:
12396                            quality = Bitmap.Config.ARGB_8888;
12397                            break;
12398                        case DRAWING_CACHE_QUALITY_HIGH:
12399                            quality = Bitmap.Config.ARGB_8888;
12400                            break;
12401                        default:
12402                            quality = Bitmap.Config.ARGB_8888;
12403                            break;
12404                    }
12405                } else {
12406                    // Optimization for translucent windows
12407                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
12408                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
12409                }
12410
12411                // Try to cleanup memory
12412                if (bitmap != null) bitmap.recycle();
12413
12414                try {
12415                    bitmap = Bitmap.createBitmap(width, height, quality);
12416                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
12417                    if (autoScale) {
12418                        mDrawingCache = bitmap;
12419                    } else {
12420                        mUnscaledDrawingCache = bitmap;
12421                    }
12422                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
12423                } catch (OutOfMemoryError e) {
12424                    // If there is not enough memory to create the bitmap cache, just
12425                    // ignore the issue as bitmap caches are not required to draw the
12426                    // view hierarchy
12427                    if (autoScale) {
12428                        mDrawingCache = null;
12429                    } else {
12430                        mUnscaledDrawingCache = null;
12431                    }
12432                    mCachingFailed = true;
12433                    return;
12434                }
12435
12436                clear = drawingCacheBackgroundColor != 0;
12437            }
12438
12439            Canvas canvas;
12440            if (attachInfo != null) {
12441                canvas = attachInfo.mCanvas;
12442                if (canvas == null) {
12443                    canvas = new Canvas();
12444                }
12445                canvas.setBitmap(bitmap);
12446                // Temporarily clobber the cached Canvas in case one of our children
12447                // is also using a drawing cache. Without this, the children would
12448                // steal the canvas by attaching their own bitmap to it and bad, bad
12449                // thing would happen (invisible views, corrupted drawings, etc.)
12450                attachInfo.mCanvas = null;
12451            } else {
12452                // This case should hopefully never or seldom happen
12453                canvas = new Canvas(bitmap);
12454            }
12455
12456            if (clear) {
12457                bitmap.eraseColor(drawingCacheBackgroundColor);
12458            }
12459
12460            computeScroll();
12461            final int restoreCount = canvas.save();
12462
12463            if (autoScale && scalingRequired) {
12464                final float scale = attachInfo.mApplicationScale;
12465                canvas.scale(scale, scale);
12466            }
12467
12468            canvas.translate(-mScrollX, -mScrollY);
12469
12470            mPrivateFlags |= DRAWN;
12471            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
12472                    mLayerType != LAYER_TYPE_NONE) {
12473                mPrivateFlags |= DRAWING_CACHE_VALID;
12474            }
12475
12476            // Fast path for layouts with no backgrounds
12477            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12478                mPrivateFlags &= ~DIRTY_MASK;
12479                dispatchDraw(canvas);
12480            } else {
12481                draw(canvas);
12482            }
12483
12484            canvas.restoreToCount(restoreCount);
12485            canvas.setBitmap(null);
12486
12487            if (attachInfo != null) {
12488                // Restore the cached Canvas for our siblings
12489                attachInfo.mCanvas = canvas;
12490            }
12491        }
12492    }
12493
12494    /**
12495     * Create a snapshot of the view into a bitmap.  We should probably make
12496     * some form of this public, but should think about the API.
12497     */
12498    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
12499        int width = mRight - mLeft;
12500        int height = mBottom - mTop;
12501
12502        final AttachInfo attachInfo = mAttachInfo;
12503        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
12504        width = (int) ((width * scale) + 0.5f);
12505        height = (int) ((height * scale) + 0.5f);
12506
12507        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
12508        if (bitmap == null) {
12509            throw new OutOfMemoryError();
12510        }
12511
12512        Resources resources = getResources();
12513        if (resources != null) {
12514            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
12515        }
12516
12517        Canvas canvas;
12518        if (attachInfo != null) {
12519            canvas = attachInfo.mCanvas;
12520            if (canvas == null) {
12521                canvas = new Canvas();
12522            }
12523            canvas.setBitmap(bitmap);
12524            // Temporarily clobber the cached Canvas in case one of our children
12525            // is also using a drawing cache. Without this, the children would
12526            // steal the canvas by attaching their own bitmap to it and bad, bad
12527            // things would happen (invisible views, corrupted drawings, etc.)
12528            attachInfo.mCanvas = null;
12529        } else {
12530            // This case should hopefully never or seldom happen
12531            canvas = new Canvas(bitmap);
12532        }
12533
12534        if ((backgroundColor & 0xff000000) != 0) {
12535            bitmap.eraseColor(backgroundColor);
12536        }
12537
12538        computeScroll();
12539        final int restoreCount = canvas.save();
12540        canvas.scale(scale, scale);
12541        canvas.translate(-mScrollX, -mScrollY);
12542
12543        // Temporarily remove the dirty mask
12544        int flags = mPrivateFlags;
12545        mPrivateFlags &= ~DIRTY_MASK;
12546
12547        // Fast path for layouts with no backgrounds
12548        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
12549            dispatchDraw(canvas);
12550        } else {
12551            draw(canvas);
12552        }
12553
12554        mPrivateFlags = flags;
12555
12556        canvas.restoreToCount(restoreCount);
12557        canvas.setBitmap(null);
12558
12559        if (attachInfo != null) {
12560            // Restore the cached Canvas for our siblings
12561            attachInfo.mCanvas = canvas;
12562        }
12563
12564        return bitmap;
12565    }
12566
12567    /**
12568     * Indicates whether this View is currently in edit mode. A View is usually
12569     * in edit mode when displayed within a developer tool. For instance, if
12570     * this View is being drawn by a visual user interface builder, this method
12571     * should return true.
12572     *
12573     * Subclasses should check the return value of this method to provide
12574     * different behaviors if their normal behavior might interfere with the
12575     * host environment. For instance: the class spawns a thread in its
12576     * constructor, the drawing code relies on device-specific features, etc.
12577     *
12578     * This method is usually checked in the drawing code of custom widgets.
12579     *
12580     * @return True if this View is in edit mode, false otherwise.
12581     */
12582    public boolean isInEditMode() {
12583        return false;
12584    }
12585
12586    /**
12587     * If the View draws content inside its padding and enables fading edges,
12588     * it needs to support padding offsets. Padding offsets are added to the
12589     * fading edges to extend the length of the fade so that it covers pixels
12590     * drawn inside the padding.
12591     *
12592     * Subclasses of this class should override this method if they need
12593     * to draw content inside the padding.
12594     *
12595     * @return True if padding offset must be applied, false otherwise.
12596     *
12597     * @see #getLeftPaddingOffset()
12598     * @see #getRightPaddingOffset()
12599     * @see #getTopPaddingOffset()
12600     * @see #getBottomPaddingOffset()
12601     *
12602     * @since CURRENT
12603     */
12604    protected boolean isPaddingOffsetRequired() {
12605        return false;
12606    }
12607
12608    /**
12609     * Amount by which to extend the left fading region. Called only when
12610     * {@link #isPaddingOffsetRequired()} returns true.
12611     *
12612     * @return The left padding offset in pixels.
12613     *
12614     * @see #isPaddingOffsetRequired()
12615     *
12616     * @since CURRENT
12617     */
12618    protected int getLeftPaddingOffset() {
12619        return 0;
12620    }
12621
12622    /**
12623     * Amount by which to extend the right fading region. Called only when
12624     * {@link #isPaddingOffsetRequired()} returns true.
12625     *
12626     * @return The right padding offset in pixels.
12627     *
12628     * @see #isPaddingOffsetRequired()
12629     *
12630     * @since CURRENT
12631     */
12632    protected int getRightPaddingOffset() {
12633        return 0;
12634    }
12635
12636    /**
12637     * Amount by which to extend the top fading region. Called only when
12638     * {@link #isPaddingOffsetRequired()} returns true.
12639     *
12640     * @return The top padding offset in pixels.
12641     *
12642     * @see #isPaddingOffsetRequired()
12643     *
12644     * @since CURRENT
12645     */
12646    protected int getTopPaddingOffset() {
12647        return 0;
12648    }
12649
12650    /**
12651     * Amount by which to extend the bottom fading region. Called only when
12652     * {@link #isPaddingOffsetRequired()} returns true.
12653     *
12654     * @return The bottom padding offset in pixels.
12655     *
12656     * @see #isPaddingOffsetRequired()
12657     *
12658     * @since CURRENT
12659     */
12660    protected int getBottomPaddingOffset() {
12661        return 0;
12662    }
12663
12664    /**
12665     * @hide
12666     * @param offsetRequired
12667     */
12668    protected int getFadeTop(boolean offsetRequired) {
12669        int top = mPaddingTop;
12670        if (offsetRequired) top += getTopPaddingOffset();
12671        return top;
12672    }
12673
12674    /**
12675     * @hide
12676     * @param offsetRequired
12677     */
12678    protected int getFadeHeight(boolean offsetRequired) {
12679        int padding = mPaddingTop;
12680        if (offsetRequired) padding += getTopPaddingOffset();
12681        return mBottom - mTop - mPaddingBottom - padding;
12682    }
12683
12684    /**
12685     * <p>Indicates whether this view is attached to a hardware accelerated
12686     * window or not.</p>
12687     *
12688     * <p>Even if this method returns true, it does not mean that every call
12689     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
12690     * accelerated {@link android.graphics.Canvas}. For instance, if this view
12691     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
12692     * window is hardware accelerated,
12693     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
12694     * return false, and this method will return true.</p>
12695     *
12696     * @return True if the view is attached to a window and the window is
12697     *         hardware accelerated; false in any other case.
12698     */
12699    public boolean isHardwareAccelerated() {
12700        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12701    }
12702
12703    /**
12704     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
12705     * case of an active Animation being run on the view.
12706     */
12707    private boolean drawAnimation(ViewGroup parent, long drawingTime,
12708            Animation a, boolean scalingRequired) {
12709        Transformation invalidationTransform;
12710        final int flags = parent.mGroupFlags;
12711        final boolean initialized = a.isInitialized();
12712        if (!initialized) {
12713            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
12714            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
12715            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
12716            onAnimationStart();
12717        }
12718
12719        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
12720        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
12721            if (parent.mInvalidationTransformation == null) {
12722                parent.mInvalidationTransformation = new Transformation();
12723            }
12724            invalidationTransform = parent.mInvalidationTransformation;
12725            a.getTransformation(drawingTime, invalidationTransform, 1f);
12726        } else {
12727            invalidationTransform = parent.mChildTransformation;
12728        }
12729
12730        if (more) {
12731            if (!a.willChangeBounds()) {
12732                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
12733                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
12734                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
12735                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
12736                    // The child need to draw an animation, potentially offscreen, so
12737                    // make sure we do not cancel invalidate requests
12738                    parent.mPrivateFlags |= DRAW_ANIMATION;
12739                    parent.invalidate(mLeft, mTop, mRight, mBottom);
12740                }
12741            } else {
12742                if (parent.mInvalidateRegion == null) {
12743                    parent.mInvalidateRegion = new RectF();
12744                }
12745                final RectF region = parent.mInvalidateRegion;
12746                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
12747                        invalidationTransform);
12748
12749                // The child need to draw an animation, potentially offscreen, so
12750                // make sure we do not cancel invalidate requests
12751                parent.mPrivateFlags |= DRAW_ANIMATION;
12752
12753                final int left = mLeft + (int) region.left;
12754                final int top = mTop + (int) region.top;
12755                parent.invalidate(left, top, left + (int) (region.width() + .5f),
12756                        top + (int) (region.height() + .5f));
12757            }
12758        }
12759        return more;
12760    }
12761
12762    /**
12763     * This method is called by getDisplayList() when a display list is created or re-rendered.
12764     * It sets or resets the current value of all properties on that display list (resetting is
12765     * necessary when a display list is being re-created, because we need to make sure that
12766     * previously-set transform values
12767     */
12768    void setDisplayListProperties(DisplayList displayList) {
12769        if (displayList != null) {
12770            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12771            displayList.setHasOverlappingRendering(hasOverlappingRendering());
12772            if (mParent instanceof ViewGroup) {
12773                displayList.setClipChildren(
12774                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
12775            }
12776            float alpha = 1;
12777            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
12778                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12779                ViewGroup parentVG = (ViewGroup) mParent;
12780                final boolean hasTransform =
12781                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
12782                if (hasTransform) {
12783                    Transformation transform = parentVG.mChildTransformation;
12784                    final int transformType = parentVG.mChildTransformation.getTransformationType();
12785                    if (transformType != Transformation.TYPE_IDENTITY) {
12786                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
12787                            alpha = transform.getAlpha();
12788                        }
12789                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
12790                            displayList.setStaticMatrix(transform.getMatrix());
12791                        }
12792                    }
12793                }
12794            }
12795            if (mTransformationInfo != null) {
12796                alpha *= mTransformationInfo.mAlpha;
12797                if (alpha < 1) {
12798                    final int multipliedAlpha = (int) (255 * alpha);
12799                    if (onSetAlpha(multipliedAlpha)) {
12800                        alpha = 1;
12801                    }
12802                }
12803                displayList.setTransformationInfo(alpha,
12804                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
12805                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
12806                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
12807                        mTransformationInfo.mScaleY);
12808                if (mTransformationInfo.mCamera == null) {
12809                    mTransformationInfo.mCamera = new Camera();
12810                    mTransformationInfo.matrix3D = new Matrix();
12811                }
12812                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
12813                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
12814                    displayList.setPivotX(getPivotX());
12815                    displayList.setPivotY(getPivotY());
12816                }
12817            } else if (alpha < 1) {
12818                displayList.setAlpha(alpha);
12819            }
12820        }
12821    }
12822
12823    /**
12824     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
12825     * This draw() method is an implementation detail and is not intended to be overridden or
12826     * to be called from anywhere else other than ViewGroup.drawChild().
12827     */
12828    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
12829        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
12830        boolean more = false;
12831        final boolean childHasIdentityMatrix = hasIdentityMatrix();
12832        final int flags = parent.mGroupFlags;
12833
12834        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
12835            parent.mChildTransformation.clear();
12836            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
12837        }
12838
12839        Transformation transformToApply = null;
12840        boolean concatMatrix = false;
12841
12842        boolean scalingRequired = false;
12843        boolean caching;
12844        int layerType = getLayerType();
12845
12846        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
12847        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
12848                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
12849            caching = true;
12850            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
12851            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
12852        } else {
12853            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
12854        }
12855
12856        final Animation a = getAnimation();
12857        if (a != null) {
12858            more = drawAnimation(parent, drawingTime, a, scalingRequired);
12859            concatMatrix = a.willChangeTransformationMatrix();
12860            if (concatMatrix) {
12861                mPrivateFlags3 |= VIEW_IS_ANIMATING_TRANSFORM;
12862            }
12863            transformToApply = parent.mChildTransformation;
12864        } else {
12865            if ((mPrivateFlags3 & VIEW_IS_ANIMATING_TRANSFORM) == VIEW_IS_ANIMATING_TRANSFORM &&
12866                    mDisplayList != null) {
12867                // No longer animating: clear out old animation matrix
12868                mDisplayList.setAnimationMatrix(null);
12869                mPrivateFlags3 &= ~VIEW_IS_ANIMATING_TRANSFORM;
12870            }
12871            if (!useDisplayListProperties &&
12872                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
12873                final boolean hasTransform =
12874                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
12875                if (hasTransform) {
12876                    final int transformType = parent.mChildTransformation.getTransformationType();
12877                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
12878                            parent.mChildTransformation : null;
12879                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
12880                }
12881            }
12882        }
12883
12884        concatMatrix |= !childHasIdentityMatrix;
12885
12886        // Sets the flag as early as possible to allow draw() implementations
12887        // to call invalidate() successfully when doing animations
12888        mPrivateFlags |= DRAWN;
12889
12890        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
12891                (mPrivateFlags & DRAW_ANIMATION) == 0) {
12892            mPrivateFlags2 |= VIEW_QUICK_REJECTED;
12893            return more;
12894        }
12895        mPrivateFlags2 &= ~VIEW_QUICK_REJECTED;
12896
12897        if (hardwareAccelerated) {
12898            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
12899            // retain the flag's value temporarily in the mRecreateDisplayList flag
12900            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
12901            mPrivateFlags &= ~INVALIDATED;
12902        }
12903
12904        DisplayList displayList = null;
12905        Bitmap cache = null;
12906        boolean hasDisplayList = false;
12907        if (caching) {
12908            if (!hardwareAccelerated) {
12909                if (layerType != LAYER_TYPE_NONE) {
12910                    layerType = LAYER_TYPE_SOFTWARE;
12911                    buildDrawingCache(true);
12912                }
12913                cache = getDrawingCache(true);
12914            } else {
12915                switch (layerType) {
12916                    case LAYER_TYPE_SOFTWARE:
12917                        if (useDisplayListProperties) {
12918                            hasDisplayList = canHaveDisplayList();
12919                        } else {
12920                            buildDrawingCache(true);
12921                            cache = getDrawingCache(true);
12922                        }
12923                        break;
12924                    case LAYER_TYPE_HARDWARE:
12925                        if (useDisplayListProperties) {
12926                            hasDisplayList = canHaveDisplayList();
12927                        }
12928                        break;
12929                    case LAYER_TYPE_NONE:
12930                        // Delay getting the display list until animation-driven alpha values are
12931                        // set up and possibly passed on to the view
12932                        hasDisplayList = canHaveDisplayList();
12933                        break;
12934                }
12935            }
12936        }
12937        useDisplayListProperties &= hasDisplayList;
12938        if (useDisplayListProperties) {
12939            displayList = getDisplayList();
12940            if (!displayList.isValid()) {
12941                // Uncommon, but possible. If a view is removed from the hierarchy during the call
12942                // to getDisplayList(), the display list will be marked invalid and we should not
12943                // try to use it again.
12944                displayList = null;
12945                hasDisplayList = false;
12946                useDisplayListProperties = false;
12947            }
12948        }
12949
12950        int sx = 0;
12951        int sy = 0;
12952        if (!hasDisplayList) {
12953            computeScroll();
12954            sx = mScrollX;
12955            sy = mScrollY;
12956        }
12957
12958        final boolean hasNoCache = cache == null || hasDisplayList;
12959        final boolean offsetForScroll = cache == null && !hasDisplayList &&
12960                layerType != LAYER_TYPE_HARDWARE;
12961
12962        int restoreTo = -1;
12963        if (!useDisplayListProperties || transformToApply != null) {
12964            restoreTo = canvas.save();
12965        }
12966        if (offsetForScroll) {
12967            canvas.translate(mLeft - sx, mTop - sy);
12968        } else {
12969            if (!useDisplayListProperties) {
12970                canvas.translate(mLeft, mTop);
12971            }
12972            if (scalingRequired) {
12973                if (useDisplayListProperties) {
12974                    // TODO: Might not need this if we put everything inside the DL
12975                    restoreTo = canvas.save();
12976                }
12977                // mAttachInfo cannot be null, otherwise scalingRequired == false
12978                final float scale = 1.0f / mAttachInfo.mApplicationScale;
12979                canvas.scale(scale, scale);
12980            }
12981        }
12982
12983        float alpha = useDisplayListProperties ? 1 : getAlpha();
12984        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
12985                (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
12986            if (transformToApply != null || !childHasIdentityMatrix) {
12987                int transX = 0;
12988                int transY = 0;
12989
12990                if (offsetForScroll) {
12991                    transX = -sx;
12992                    transY = -sy;
12993                }
12994
12995                if (transformToApply != null) {
12996                    if (concatMatrix) {
12997                        if (useDisplayListProperties) {
12998                            displayList.setAnimationMatrix(transformToApply.getMatrix());
12999                        } else {
13000                            // Undo the scroll translation, apply the transformation matrix,
13001                            // then redo the scroll translate to get the correct result.
13002                            canvas.translate(-transX, -transY);
13003                            canvas.concat(transformToApply.getMatrix());
13004                            canvas.translate(transX, transY);
13005                        }
13006                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13007                    }
13008
13009                    float transformAlpha = transformToApply.getAlpha();
13010                    if (transformAlpha < 1) {
13011                        alpha *= transformAlpha;
13012                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13013                    }
13014                }
13015
13016                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13017                    canvas.translate(-transX, -transY);
13018                    canvas.concat(getMatrix());
13019                    canvas.translate(transX, transY);
13020                }
13021            }
13022
13023            // Deal with alpha if it is or used to be <1
13024            if (alpha < 1 ||
13025                    (mPrivateFlags3 & VIEW_IS_ANIMATING_ALPHA) == VIEW_IS_ANIMATING_ALPHA) {
13026                if (alpha < 1) {
13027                    mPrivateFlags3 |= VIEW_IS_ANIMATING_ALPHA;
13028                } else {
13029                    mPrivateFlags3 &= ~VIEW_IS_ANIMATING_ALPHA;
13030                }
13031                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13032                if (hasNoCache) {
13033                    final int multipliedAlpha = (int) (255 * alpha);
13034                    if (!onSetAlpha(multipliedAlpha)) {
13035                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13036                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13037                                layerType != LAYER_TYPE_NONE) {
13038                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13039                        }
13040                        if (useDisplayListProperties) {
13041                            displayList.setAlpha(alpha * getAlpha());
13042                        } else  if (layerType == LAYER_TYPE_NONE) {
13043                            final int scrollX = hasDisplayList ? 0 : sx;
13044                            final int scrollY = hasDisplayList ? 0 : sy;
13045                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13046                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13047                        }
13048                    } else {
13049                        // Alpha is handled by the child directly, clobber the layer's alpha
13050                        mPrivateFlags |= ALPHA_SET;
13051                    }
13052                }
13053            }
13054        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13055            onSetAlpha(255);
13056            mPrivateFlags &= ~ALPHA_SET;
13057        }
13058
13059        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13060                !useDisplayListProperties) {
13061            if (offsetForScroll) {
13062                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13063            } else {
13064                if (!scalingRequired || cache == null) {
13065                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13066                } else {
13067                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13068                }
13069            }
13070        }
13071
13072        if (!useDisplayListProperties && hasDisplayList) {
13073            displayList = getDisplayList();
13074            if (!displayList.isValid()) {
13075                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13076                // to getDisplayList(), the display list will be marked invalid and we should not
13077                // try to use it again.
13078                displayList = null;
13079                hasDisplayList = false;
13080            }
13081        }
13082
13083        if (hasNoCache) {
13084            boolean layerRendered = false;
13085            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13086                final HardwareLayer layer = getHardwareLayer();
13087                if (layer != null && layer.isValid()) {
13088                    mLayerPaint.setAlpha((int) (alpha * 255));
13089                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13090                    layerRendered = true;
13091                } else {
13092                    final int scrollX = hasDisplayList ? 0 : sx;
13093                    final int scrollY = hasDisplayList ? 0 : sy;
13094                    canvas.saveLayer(scrollX, scrollY,
13095                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13096                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13097                }
13098            }
13099
13100            if (!layerRendered) {
13101                if (!hasDisplayList) {
13102                    // Fast path for layouts with no backgrounds
13103                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
13104                        mPrivateFlags &= ~DIRTY_MASK;
13105                        dispatchDraw(canvas);
13106                    } else {
13107                        draw(canvas);
13108                    }
13109                } else {
13110                    mPrivateFlags &= ~DIRTY_MASK;
13111                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13112                }
13113            }
13114        } else if (cache != null) {
13115            mPrivateFlags &= ~DIRTY_MASK;
13116            Paint cachePaint;
13117
13118            if (layerType == LAYER_TYPE_NONE) {
13119                cachePaint = parent.mCachePaint;
13120                if (cachePaint == null) {
13121                    cachePaint = new Paint();
13122                    cachePaint.setDither(false);
13123                    parent.mCachePaint = cachePaint;
13124                }
13125                if (alpha < 1) {
13126                    cachePaint.setAlpha((int) (alpha * 255));
13127                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13128                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13129                    cachePaint.setAlpha(255);
13130                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13131                }
13132            } else {
13133                cachePaint = mLayerPaint;
13134                cachePaint.setAlpha((int) (alpha * 255));
13135            }
13136            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13137        }
13138
13139        if (restoreTo >= 0) {
13140            canvas.restoreToCount(restoreTo);
13141        }
13142
13143        if (a != null && !more) {
13144            if (!hardwareAccelerated && !a.getFillAfter()) {
13145                onSetAlpha(255);
13146            }
13147            parent.finishAnimatingView(this, a);
13148        }
13149
13150        if (more && hardwareAccelerated) {
13151            // invalidation is the trigger to recreate display lists, so if we're using
13152            // display lists to render, force an invalidate to allow the animation to
13153            // continue drawing another frame
13154            parent.invalidate(true);
13155            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
13156                // alpha animations should cause the child to recreate its display list
13157                invalidate(true);
13158            }
13159        }
13160
13161        mRecreateDisplayList = false;
13162
13163        return more;
13164    }
13165
13166    /**
13167     * Manually render this view (and all of its children) to the given Canvas.
13168     * The view must have already done a full layout before this function is
13169     * called.  When implementing a view, implement
13170     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13171     * If you do need to override this method, call the superclass version.
13172     *
13173     * @param canvas The Canvas to which the View is rendered.
13174     */
13175    public void draw(Canvas canvas) {
13176        final int privateFlags = mPrivateFlags;
13177        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
13178                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13179        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
13180
13181        /*
13182         * Draw traversal performs several drawing steps which must be executed
13183         * in the appropriate order:
13184         *
13185         *      1. Draw the background
13186         *      2. If necessary, save the canvas' layers to prepare for fading
13187         *      3. Draw view's content
13188         *      4. Draw children
13189         *      5. If necessary, draw the fading edges and restore layers
13190         *      6. Draw decorations (scrollbars for instance)
13191         */
13192
13193        // Step 1, draw the background, if needed
13194        int saveCount;
13195
13196        if (!dirtyOpaque) {
13197            final Drawable background = mBackground;
13198            if (background != null) {
13199                final int scrollX = mScrollX;
13200                final int scrollY = mScrollY;
13201
13202                if (mBackgroundSizeChanged) {
13203                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13204                    mBackgroundSizeChanged = false;
13205                }
13206
13207                if ((scrollX | scrollY) == 0) {
13208                    background.draw(canvas);
13209                } else {
13210                    canvas.translate(scrollX, scrollY);
13211                    background.draw(canvas);
13212                    canvas.translate(-scrollX, -scrollY);
13213                }
13214            }
13215        }
13216
13217        // skip step 2 & 5 if possible (common case)
13218        final int viewFlags = mViewFlags;
13219        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13220        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13221        if (!verticalEdges && !horizontalEdges) {
13222            // Step 3, draw the content
13223            if (!dirtyOpaque) onDraw(canvas);
13224
13225            // Step 4, draw the children
13226            dispatchDraw(canvas);
13227
13228            // Step 6, draw decorations (scrollbars)
13229            onDrawScrollBars(canvas);
13230
13231            // we're done...
13232            return;
13233        }
13234
13235        /*
13236         * Here we do the full fledged routine...
13237         * (this is an uncommon case where speed matters less,
13238         * this is why we repeat some of the tests that have been
13239         * done above)
13240         */
13241
13242        boolean drawTop = false;
13243        boolean drawBottom = false;
13244        boolean drawLeft = false;
13245        boolean drawRight = false;
13246
13247        float topFadeStrength = 0.0f;
13248        float bottomFadeStrength = 0.0f;
13249        float leftFadeStrength = 0.0f;
13250        float rightFadeStrength = 0.0f;
13251
13252        // Step 2, save the canvas' layers
13253        int paddingLeft = mPaddingLeft;
13254
13255        final boolean offsetRequired = isPaddingOffsetRequired();
13256        if (offsetRequired) {
13257            paddingLeft += getLeftPaddingOffset();
13258        }
13259
13260        int left = mScrollX + paddingLeft;
13261        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13262        int top = mScrollY + getFadeTop(offsetRequired);
13263        int bottom = top + getFadeHeight(offsetRequired);
13264
13265        if (offsetRequired) {
13266            right += getRightPaddingOffset();
13267            bottom += getBottomPaddingOffset();
13268        }
13269
13270        final ScrollabilityCache scrollabilityCache = mScrollCache;
13271        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13272        int length = (int) fadeHeight;
13273
13274        // clip the fade length if top and bottom fades overlap
13275        // overlapping fades produce odd-looking artifacts
13276        if (verticalEdges && (top + length > bottom - length)) {
13277            length = (bottom - top) / 2;
13278        }
13279
13280        // also clip horizontal fades if necessary
13281        if (horizontalEdges && (left + length > right - length)) {
13282            length = (right - left) / 2;
13283        }
13284
13285        if (verticalEdges) {
13286            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13287            drawTop = topFadeStrength * fadeHeight > 1.0f;
13288            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13289            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13290        }
13291
13292        if (horizontalEdges) {
13293            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13294            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13295            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13296            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13297        }
13298
13299        saveCount = canvas.getSaveCount();
13300
13301        int solidColor = getSolidColor();
13302        if (solidColor == 0) {
13303            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13304
13305            if (drawTop) {
13306                canvas.saveLayer(left, top, right, top + length, null, flags);
13307            }
13308
13309            if (drawBottom) {
13310                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13311            }
13312
13313            if (drawLeft) {
13314                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13315            }
13316
13317            if (drawRight) {
13318                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13319            }
13320        } else {
13321            scrollabilityCache.setFadeColor(solidColor);
13322        }
13323
13324        // Step 3, draw the content
13325        if (!dirtyOpaque) onDraw(canvas);
13326
13327        // Step 4, draw the children
13328        dispatchDraw(canvas);
13329
13330        // Step 5, draw the fade effect and restore layers
13331        final Paint p = scrollabilityCache.paint;
13332        final Matrix matrix = scrollabilityCache.matrix;
13333        final Shader fade = scrollabilityCache.shader;
13334
13335        if (drawTop) {
13336            matrix.setScale(1, fadeHeight * topFadeStrength);
13337            matrix.postTranslate(left, top);
13338            fade.setLocalMatrix(matrix);
13339            canvas.drawRect(left, top, right, top + length, p);
13340        }
13341
13342        if (drawBottom) {
13343            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13344            matrix.postRotate(180);
13345            matrix.postTranslate(left, bottom);
13346            fade.setLocalMatrix(matrix);
13347            canvas.drawRect(left, bottom - length, right, bottom, p);
13348        }
13349
13350        if (drawLeft) {
13351            matrix.setScale(1, fadeHeight * leftFadeStrength);
13352            matrix.postRotate(-90);
13353            matrix.postTranslate(left, top);
13354            fade.setLocalMatrix(matrix);
13355            canvas.drawRect(left, top, left + length, bottom, p);
13356        }
13357
13358        if (drawRight) {
13359            matrix.setScale(1, fadeHeight * rightFadeStrength);
13360            matrix.postRotate(90);
13361            matrix.postTranslate(right, top);
13362            fade.setLocalMatrix(matrix);
13363            canvas.drawRect(right - length, top, right, bottom, p);
13364        }
13365
13366        canvas.restoreToCount(saveCount);
13367
13368        // Step 6, draw decorations (scrollbars)
13369        onDrawScrollBars(canvas);
13370    }
13371
13372    /**
13373     * Override this if your view is known to always be drawn on top of a solid color background,
13374     * and needs to draw fading edges. Returning a non-zero color enables the view system to
13375     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
13376     * should be set to 0xFF.
13377     *
13378     * @see #setVerticalFadingEdgeEnabled(boolean)
13379     * @see #setHorizontalFadingEdgeEnabled(boolean)
13380     *
13381     * @return The known solid color background for this view, or 0 if the color may vary
13382     */
13383    @ViewDebug.ExportedProperty(category = "drawing")
13384    public int getSolidColor() {
13385        return 0;
13386    }
13387
13388    /**
13389     * Build a human readable string representation of the specified view flags.
13390     *
13391     * @param flags the view flags to convert to a string
13392     * @return a String representing the supplied flags
13393     */
13394    private static String printFlags(int flags) {
13395        String output = "";
13396        int numFlags = 0;
13397        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
13398            output += "TAKES_FOCUS";
13399            numFlags++;
13400        }
13401
13402        switch (flags & VISIBILITY_MASK) {
13403        case INVISIBLE:
13404            if (numFlags > 0) {
13405                output += " ";
13406            }
13407            output += "INVISIBLE";
13408            // USELESS HERE numFlags++;
13409            break;
13410        case GONE:
13411            if (numFlags > 0) {
13412                output += " ";
13413            }
13414            output += "GONE";
13415            // USELESS HERE numFlags++;
13416            break;
13417        default:
13418            break;
13419        }
13420        return output;
13421    }
13422
13423    /**
13424     * Build a human readable string representation of the specified private
13425     * view flags.
13426     *
13427     * @param privateFlags the private view flags to convert to a string
13428     * @return a String representing the supplied flags
13429     */
13430    private static String printPrivateFlags(int privateFlags) {
13431        String output = "";
13432        int numFlags = 0;
13433
13434        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
13435            output += "WANTS_FOCUS";
13436            numFlags++;
13437        }
13438
13439        if ((privateFlags & FOCUSED) == FOCUSED) {
13440            if (numFlags > 0) {
13441                output += " ";
13442            }
13443            output += "FOCUSED";
13444            numFlags++;
13445        }
13446
13447        if ((privateFlags & SELECTED) == SELECTED) {
13448            if (numFlags > 0) {
13449                output += " ";
13450            }
13451            output += "SELECTED";
13452            numFlags++;
13453        }
13454
13455        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
13456            if (numFlags > 0) {
13457                output += " ";
13458            }
13459            output += "IS_ROOT_NAMESPACE";
13460            numFlags++;
13461        }
13462
13463        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
13464            if (numFlags > 0) {
13465                output += " ";
13466            }
13467            output += "HAS_BOUNDS";
13468            numFlags++;
13469        }
13470
13471        if ((privateFlags & DRAWN) == DRAWN) {
13472            if (numFlags > 0) {
13473                output += " ";
13474            }
13475            output += "DRAWN";
13476            // USELESS HERE numFlags++;
13477        }
13478        return output;
13479    }
13480
13481    /**
13482     * <p>Indicates whether or not this view's layout will be requested during
13483     * the next hierarchy layout pass.</p>
13484     *
13485     * @return true if the layout will be forced during next layout pass
13486     */
13487    public boolean isLayoutRequested() {
13488        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
13489    }
13490
13491    /**
13492     * Assign a size and position to a view and all of its
13493     * descendants
13494     *
13495     * <p>This is the second phase of the layout mechanism.
13496     * (The first is measuring). In this phase, each parent calls
13497     * layout on all of its children to position them.
13498     * This is typically done using the child measurements
13499     * that were stored in the measure pass().</p>
13500     *
13501     * <p>Derived classes should not override this method.
13502     * Derived classes with children should override
13503     * onLayout. In that method, they should
13504     * call layout on each of their children.</p>
13505     *
13506     * @param l Left position, relative to parent
13507     * @param t Top position, relative to parent
13508     * @param r Right position, relative to parent
13509     * @param b Bottom position, relative to parent
13510     */
13511    @SuppressWarnings({"unchecked"})
13512    public void layout(int l, int t, int r, int b) {
13513        int oldL = mLeft;
13514        int oldT = mTop;
13515        int oldB = mBottom;
13516        int oldR = mRight;
13517        boolean changed = setFrame(l, t, r, b);
13518        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
13519            onLayout(changed, l, t, r, b);
13520            mPrivateFlags &= ~LAYOUT_REQUIRED;
13521
13522            ListenerInfo li = mListenerInfo;
13523            if (li != null && li.mOnLayoutChangeListeners != null) {
13524                ArrayList<OnLayoutChangeListener> listenersCopy =
13525                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
13526                int numListeners = listenersCopy.size();
13527                for (int i = 0; i < numListeners; ++i) {
13528                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
13529                }
13530            }
13531        }
13532        mPrivateFlags &= ~FORCE_LAYOUT;
13533    }
13534
13535    /**
13536     * Called from layout when this view should
13537     * assign a size and position to each of its children.
13538     *
13539     * Derived classes with children should override
13540     * this method and call layout on each of
13541     * their children.
13542     * @param changed This is a new size or position for this view
13543     * @param left Left position, relative to parent
13544     * @param top Top position, relative to parent
13545     * @param right Right position, relative to parent
13546     * @param bottom Bottom position, relative to parent
13547     */
13548    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
13549    }
13550
13551    /**
13552     * Assign a size and position to this view.
13553     *
13554     * This is called from layout.
13555     *
13556     * @param left Left position, relative to parent
13557     * @param top Top position, relative to parent
13558     * @param right Right position, relative to parent
13559     * @param bottom Bottom position, relative to parent
13560     * @return true if the new size and position are different than the
13561     *         previous ones
13562     * {@hide}
13563     */
13564    protected boolean setFrame(int left, int top, int right, int bottom) {
13565        boolean changed = false;
13566
13567        if (DBG) {
13568            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
13569                    + right + "," + bottom + ")");
13570        }
13571
13572        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
13573            changed = true;
13574
13575            // Remember our drawn bit
13576            int drawn = mPrivateFlags & DRAWN;
13577
13578            int oldWidth = mRight - mLeft;
13579            int oldHeight = mBottom - mTop;
13580            int newWidth = right - left;
13581            int newHeight = bottom - top;
13582            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
13583
13584            // Invalidate our old position
13585            invalidate(sizeChanged);
13586
13587            mLeft = left;
13588            mTop = top;
13589            mRight = right;
13590            mBottom = bottom;
13591            if (mDisplayList != null) {
13592                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13593            }
13594
13595            mPrivateFlags |= HAS_BOUNDS;
13596
13597
13598            if (sizeChanged) {
13599                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
13600                    // A change in dimension means an auto-centered pivot point changes, too
13601                    if (mTransformationInfo != null) {
13602                        mTransformationInfo.mMatrixDirty = true;
13603                    }
13604                }
13605                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
13606            }
13607
13608            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
13609                // If we are visible, force the DRAWN bit to on so that
13610                // this invalidate will go through (at least to our parent).
13611                // This is because someone may have invalidated this view
13612                // before this call to setFrame came in, thereby clearing
13613                // the DRAWN bit.
13614                mPrivateFlags |= DRAWN;
13615                invalidate(sizeChanged);
13616                // parent display list may need to be recreated based on a change in the bounds
13617                // of any child
13618                invalidateParentCaches();
13619            }
13620
13621            // Reset drawn bit to original value (invalidate turns it off)
13622            mPrivateFlags |= drawn;
13623
13624            mBackgroundSizeChanged = true;
13625        }
13626        return changed;
13627    }
13628
13629    /**
13630     * Finalize inflating a view from XML.  This is called as the last phase
13631     * of inflation, after all child views have been added.
13632     *
13633     * <p>Even if the subclass overrides onFinishInflate, they should always be
13634     * sure to call the super method, so that we get called.
13635     */
13636    protected void onFinishInflate() {
13637    }
13638
13639    /**
13640     * Returns the resources associated with this view.
13641     *
13642     * @return Resources object.
13643     */
13644    public Resources getResources() {
13645        return mResources;
13646    }
13647
13648    /**
13649     * Invalidates the specified Drawable.
13650     *
13651     * @param drawable the drawable to invalidate
13652     */
13653    public void invalidateDrawable(Drawable drawable) {
13654        if (verifyDrawable(drawable)) {
13655            final Rect dirty = drawable.getBounds();
13656            final int scrollX = mScrollX;
13657            final int scrollY = mScrollY;
13658
13659            invalidate(dirty.left + scrollX, dirty.top + scrollY,
13660                    dirty.right + scrollX, dirty.bottom + scrollY);
13661        }
13662    }
13663
13664    /**
13665     * Schedules an action on a drawable to occur at a specified time.
13666     *
13667     * @param who the recipient of the action
13668     * @param what the action to run on the drawable
13669     * @param when the time at which the action must occur. Uses the
13670     *        {@link SystemClock#uptimeMillis} timebase.
13671     */
13672    public void scheduleDrawable(Drawable who, Runnable what, long when) {
13673        if (verifyDrawable(who) && what != null) {
13674            final long delay = when - SystemClock.uptimeMillis();
13675            if (mAttachInfo != null) {
13676                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
13677                        Choreographer.CALLBACK_ANIMATION, what, who,
13678                        Choreographer.subtractFrameDelay(delay));
13679            } else {
13680                ViewRootImpl.getRunQueue().postDelayed(what, delay);
13681            }
13682        }
13683    }
13684
13685    /**
13686     * Cancels a scheduled action on a drawable.
13687     *
13688     * @param who the recipient of the action
13689     * @param what the action to cancel
13690     */
13691    public void unscheduleDrawable(Drawable who, Runnable what) {
13692        if (verifyDrawable(who) && what != null) {
13693            if (mAttachInfo != null) {
13694                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13695                        Choreographer.CALLBACK_ANIMATION, what, who);
13696            } else {
13697                ViewRootImpl.getRunQueue().removeCallbacks(what);
13698            }
13699        }
13700    }
13701
13702    /**
13703     * Unschedule any events associated with the given Drawable.  This can be
13704     * used when selecting a new Drawable into a view, so that the previous
13705     * one is completely unscheduled.
13706     *
13707     * @param who The Drawable to unschedule.
13708     *
13709     * @see #drawableStateChanged
13710     */
13711    public void unscheduleDrawable(Drawable who) {
13712        if (mAttachInfo != null && who != null) {
13713            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
13714                    Choreographer.CALLBACK_ANIMATION, null, who);
13715        }
13716    }
13717
13718    /**
13719     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
13720     * that the View directionality can and will be resolved before its Drawables.
13721     *
13722     * Will call {@link View#onResolveDrawables} when resolution is done.
13723     */
13724    public void resolveDrawables() {
13725        if (mBackground != null) {
13726            mBackground.setLayoutDirection(getResolvedLayoutDirection());
13727        }
13728        onResolveDrawables(getResolvedLayoutDirection());
13729    }
13730
13731    /**
13732     * Called when layout direction has been resolved.
13733     *
13734     * The default implementation does nothing.
13735     *
13736     * @param layoutDirection The resolved layout direction.
13737     *
13738     * @see {@link #LAYOUT_DIRECTION_LTR}
13739     * @see {@link #LAYOUT_DIRECTION_RTL}
13740     */
13741    public void onResolveDrawables(int layoutDirection) {
13742    }
13743
13744    /**
13745     * If your view subclass is displaying its own Drawable objects, it should
13746     * override this function and return true for any Drawable it is
13747     * displaying.  This allows animations for those drawables to be
13748     * scheduled.
13749     *
13750     * <p>Be sure to call through to the super class when overriding this
13751     * function.
13752     *
13753     * @param who The Drawable to verify.  Return true if it is one you are
13754     *            displaying, else return the result of calling through to the
13755     *            super class.
13756     *
13757     * @return boolean If true than the Drawable is being displayed in the
13758     *         view; else false and it is not allowed to animate.
13759     *
13760     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
13761     * @see #drawableStateChanged()
13762     */
13763    protected boolean verifyDrawable(Drawable who) {
13764        return who == mBackground;
13765    }
13766
13767    /**
13768     * This function is called whenever the state of the view changes in such
13769     * a way that it impacts the state of drawables being shown.
13770     *
13771     * <p>Be sure to call through to the superclass when overriding this
13772     * function.
13773     *
13774     * @see Drawable#setState(int[])
13775     */
13776    protected void drawableStateChanged() {
13777        Drawable d = mBackground;
13778        if (d != null && d.isStateful()) {
13779            d.setState(getDrawableState());
13780        }
13781    }
13782
13783    /**
13784     * Call this to force a view to update its drawable state. This will cause
13785     * drawableStateChanged to be called on this view. Views that are interested
13786     * in the new state should call getDrawableState.
13787     *
13788     * @see #drawableStateChanged
13789     * @see #getDrawableState
13790     */
13791    public void refreshDrawableState() {
13792        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
13793        drawableStateChanged();
13794
13795        ViewParent parent = mParent;
13796        if (parent != null) {
13797            parent.childDrawableStateChanged(this);
13798        }
13799    }
13800
13801    /**
13802     * Return an array of resource IDs of the drawable states representing the
13803     * current state of the view.
13804     *
13805     * @return The current drawable state
13806     *
13807     * @see Drawable#setState(int[])
13808     * @see #drawableStateChanged()
13809     * @see #onCreateDrawableState(int)
13810     */
13811    public final int[] getDrawableState() {
13812        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
13813            return mDrawableState;
13814        } else {
13815            mDrawableState = onCreateDrawableState(0);
13816            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
13817            return mDrawableState;
13818        }
13819    }
13820
13821    /**
13822     * Generate the new {@link android.graphics.drawable.Drawable} state for
13823     * this view. This is called by the view
13824     * system when the cached Drawable state is determined to be invalid.  To
13825     * retrieve the current state, you should use {@link #getDrawableState}.
13826     *
13827     * @param extraSpace if non-zero, this is the number of extra entries you
13828     * would like in the returned array in which you can place your own
13829     * states.
13830     *
13831     * @return Returns an array holding the current {@link Drawable} state of
13832     * the view.
13833     *
13834     * @see #mergeDrawableStates(int[], int[])
13835     */
13836    protected int[] onCreateDrawableState(int extraSpace) {
13837        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
13838                mParent instanceof View) {
13839            return ((View) mParent).onCreateDrawableState(extraSpace);
13840        }
13841
13842        int[] drawableState;
13843
13844        int privateFlags = mPrivateFlags;
13845
13846        int viewStateIndex = 0;
13847        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
13848        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
13849        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
13850        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
13851        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
13852        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
13853        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
13854                HardwareRenderer.isAvailable()) {
13855            // This is set if HW acceleration is requested, even if the current
13856            // process doesn't allow it.  This is just to allow app preview
13857            // windows to better match their app.
13858            viewStateIndex |= VIEW_STATE_ACCELERATED;
13859        }
13860        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
13861
13862        final int privateFlags2 = mPrivateFlags2;
13863        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
13864        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
13865
13866        drawableState = VIEW_STATE_SETS[viewStateIndex];
13867
13868        //noinspection ConstantIfStatement
13869        if (false) {
13870            Log.i("View", "drawableStateIndex=" + viewStateIndex);
13871            Log.i("View", toString()
13872                    + " pressed=" + ((privateFlags & PRESSED) != 0)
13873                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
13874                    + " fo=" + hasFocus()
13875                    + " sl=" + ((privateFlags & SELECTED) != 0)
13876                    + " wf=" + hasWindowFocus()
13877                    + ": " + Arrays.toString(drawableState));
13878        }
13879
13880        if (extraSpace == 0) {
13881            return drawableState;
13882        }
13883
13884        final int[] fullState;
13885        if (drawableState != null) {
13886            fullState = new int[drawableState.length + extraSpace];
13887            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
13888        } else {
13889            fullState = new int[extraSpace];
13890        }
13891
13892        return fullState;
13893    }
13894
13895    /**
13896     * Merge your own state values in <var>additionalState</var> into the base
13897     * state values <var>baseState</var> that were returned by
13898     * {@link #onCreateDrawableState(int)}.
13899     *
13900     * @param baseState The base state values returned by
13901     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
13902     * own additional state values.
13903     *
13904     * @param additionalState The additional state values you would like
13905     * added to <var>baseState</var>; this array is not modified.
13906     *
13907     * @return As a convenience, the <var>baseState</var> array you originally
13908     * passed into the function is returned.
13909     *
13910     * @see #onCreateDrawableState(int)
13911     */
13912    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
13913        final int N = baseState.length;
13914        int i = N - 1;
13915        while (i >= 0 && baseState[i] == 0) {
13916            i--;
13917        }
13918        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
13919        return baseState;
13920    }
13921
13922    /**
13923     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
13924     * on all Drawable objects associated with this view.
13925     */
13926    public void jumpDrawablesToCurrentState() {
13927        if (mBackground != null) {
13928            mBackground.jumpToCurrentState();
13929        }
13930    }
13931
13932    /**
13933     * Sets the background color for this view.
13934     * @param color the color of the background
13935     */
13936    @RemotableViewMethod
13937    public void setBackgroundColor(int color) {
13938        if (mBackground instanceof ColorDrawable) {
13939            ((ColorDrawable) mBackground).setColor(color);
13940            computeOpaqueFlags();
13941        } else {
13942            setBackground(new ColorDrawable(color));
13943        }
13944    }
13945
13946    /**
13947     * Set the background to a given resource. The resource should refer to
13948     * a Drawable object or 0 to remove the background.
13949     * @param resid The identifier of the resource.
13950     *
13951     * @attr ref android.R.styleable#View_background
13952     */
13953    @RemotableViewMethod
13954    public void setBackgroundResource(int resid) {
13955        if (resid != 0 && resid == mBackgroundResource) {
13956            return;
13957        }
13958
13959        Drawable d= null;
13960        if (resid != 0) {
13961            d = mResources.getDrawable(resid);
13962        }
13963        setBackground(d);
13964
13965        mBackgroundResource = resid;
13966    }
13967
13968    /**
13969     * Set the background to a given Drawable, or remove the background. If the
13970     * background has padding, this View's padding is set to the background's
13971     * padding. However, when a background is removed, this View's padding isn't
13972     * touched. If setting the padding is desired, please use
13973     * {@link #setPadding(int, int, int, int)}.
13974     *
13975     * @param background The Drawable to use as the background, or null to remove the
13976     *        background
13977     */
13978    public void setBackground(Drawable background) {
13979        //noinspection deprecation
13980        setBackgroundDrawable(background);
13981    }
13982
13983    /**
13984     * @deprecated use {@link #setBackground(Drawable)} instead
13985     */
13986    @Deprecated
13987    public void setBackgroundDrawable(Drawable background) {
13988        computeOpaqueFlags();
13989
13990        if (background == mBackground) {
13991            return;
13992        }
13993
13994        boolean requestLayout = false;
13995
13996        mBackgroundResource = 0;
13997
13998        /*
13999         * Regardless of whether we're setting a new background or not, we want
14000         * to clear the previous drawable.
14001         */
14002        if (mBackground != null) {
14003            mBackground.setCallback(null);
14004            unscheduleDrawable(mBackground);
14005        }
14006
14007        if (background != null) {
14008            Rect padding = sThreadLocal.get();
14009            if (padding == null) {
14010                padding = new Rect();
14011                sThreadLocal.set(padding);
14012            }
14013            background.setLayoutDirection(getResolvedLayoutDirection());
14014            if (background.getPadding(padding)) {
14015                switch (background.getLayoutDirection()) {
14016                    case LAYOUT_DIRECTION_RTL:
14017                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
14018                        break;
14019                    case LAYOUT_DIRECTION_LTR:
14020                    default:
14021                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
14022                }
14023            }
14024
14025            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14026            // if it has a different minimum size, we should layout again
14027            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14028                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14029                requestLayout = true;
14030            }
14031
14032            background.setCallback(this);
14033            if (background.isStateful()) {
14034                background.setState(getDrawableState());
14035            }
14036            background.setVisible(getVisibility() == VISIBLE, false);
14037            mBackground = background;
14038
14039            if ((mPrivateFlags & SKIP_DRAW) != 0) {
14040                mPrivateFlags &= ~SKIP_DRAW;
14041                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
14042                requestLayout = true;
14043            }
14044        } else {
14045            /* Remove the background */
14046            mBackground = null;
14047
14048            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
14049                /*
14050                 * This view ONLY drew the background before and we're removing
14051                 * the background, so now it won't draw anything
14052                 * (hence we SKIP_DRAW)
14053                 */
14054                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
14055                mPrivateFlags |= SKIP_DRAW;
14056            }
14057
14058            /*
14059             * When the background is set, we try to apply its padding to this
14060             * View. When the background is removed, we don't touch this View's
14061             * padding. This is noted in the Javadocs. Hence, we don't need to
14062             * requestLayout(), the invalidate() below is sufficient.
14063             */
14064
14065            // The old background's minimum size could have affected this
14066            // View's layout, so let's requestLayout
14067            requestLayout = true;
14068        }
14069
14070        computeOpaqueFlags();
14071
14072        if (requestLayout) {
14073            requestLayout();
14074        }
14075
14076        mBackgroundSizeChanged = true;
14077        invalidate(true);
14078    }
14079
14080    /**
14081     * Gets the background drawable
14082     *
14083     * @return The drawable used as the background for this view, if any.
14084     *
14085     * @see #setBackground(Drawable)
14086     *
14087     * @attr ref android.R.styleable#View_background
14088     */
14089    public Drawable getBackground() {
14090        return mBackground;
14091    }
14092
14093    /**
14094     * Sets the padding. The view may add on the space required to display
14095     * the scrollbars, depending on the style and visibility of the scrollbars.
14096     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14097     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14098     * from the values set in this call.
14099     *
14100     * @attr ref android.R.styleable#View_padding
14101     * @attr ref android.R.styleable#View_paddingBottom
14102     * @attr ref android.R.styleable#View_paddingLeft
14103     * @attr ref android.R.styleable#View_paddingRight
14104     * @attr ref android.R.styleable#View_paddingTop
14105     * @param left the left padding in pixels
14106     * @param top the top padding in pixels
14107     * @param right the right padding in pixels
14108     * @param bottom the bottom padding in pixels
14109     */
14110    public void setPadding(int left, int top, int right, int bottom) {
14111        mUserPaddingStart = -1;
14112        mUserPaddingEnd = -1;
14113        mUserPaddingRelative = false;
14114
14115        internalSetPadding(left, top, right, bottom);
14116    }
14117
14118    private void internalSetPadding(int left, int top, int right, int bottom) {
14119        mUserPaddingLeft = left;
14120        mUserPaddingRight = right;
14121        mUserPaddingBottom = bottom;
14122
14123        final int viewFlags = mViewFlags;
14124        boolean changed = false;
14125
14126        // Common case is there are no scroll bars.
14127        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14128            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14129                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14130                        ? 0 : getVerticalScrollbarWidth();
14131                switch (mVerticalScrollbarPosition) {
14132                    case SCROLLBAR_POSITION_DEFAULT:
14133                        if (isLayoutRtl()) {
14134                            left += offset;
14135                        } else {
14136                            right += offset;
14137                        }
14138                        break;
14139                    case SCROLLBAR_POSITION_RIGHT:
14140                        right += offset;
14141                        break;
14142                    case SCROLLBAR_POSITION_LEFT:
14143                        left += offset;
14144                        break;
14145                }
14146            }
14147            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14148                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14149                        ? 0 : getHorizontalScrollbarHeight();
14150            }
14151        }
14152
14153        if (mPaddingLeft != left) {
14154            changed = true;
14155            mPaddingLeft = left;
14156        }
14157        if (mPaddingTop != top) {
14158            changed = true;
14159            mPaddingTop = top;
14160        }
14161        if (mPaddingRight != right) {
14162            changed = true;
14163            mPaddingRight = right;
14164        }
14165        if (mPaddingBottom != bottom) {
14166            changed = true;
14167            mPaddingBottom = bottom;
14168        }
14169
14170        if (changed) {
14171            requestLayout();
14172        }
14173    }
14174
14175    /**
14176     * Sets the relative padding. The view may add on the space required to display
14177     * the scrollbars, depending on the style and visibility of the scrollbars.
14178     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14179     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14180     * from the values set in this call.
14181     *
14182     * @attr ref android.R.styleable#View_padding
14183     * @attr ref android.R.styleable#View_paddingBottom
14184     * @attr ref android.R.styleable#View_paddingStart
14185     * @attr ref android.R.styleable#View_paddingEnd
14186     * @attr ref android.R.styleable#View_paddingTop
14187     * @param start the start padding in pixels
14188     * @param top the top padding in pixels
14189     * @param end the end padding in pixels
14190     * @param bottom the bottom padding in pixels
14191     */
14192    public void setPaddingRelative(int start, int top, int end, int bottom) {
14193        mUserPaddingStart = start;
14194        mUserPaddingEnd = end;
14195        mUserPaddingRelative = true;
14196
14197        switch(getResolvedLayoutDirection()) {
14198            case LAYOUT_DIRECTION_RTL:
14199                internalSetPadding(end, top, start, bottom);
14200                break;
14201            case LAYOUT_DIRECTION_LTR:
14202            default:
14203                internalSetPadding(start, top, end, bottom);
14204        }
14205    }
14206
14207    /**
14208     * Returns the top padding of this view.
14209     *
14210     * @return the top padding in pixels
14211     */
14212    public int getPaddingTop() {
14213        return mPaddingTop;
14214    }
14215
14216    /**
14217     * Returns the bottom padding of this view. If there are inset and enabled
14218     * scrollbars, this value may include the space required to display the
14219     * scrollbars as well.
14220     *
14221     * @return the bottom padding in pixels
14222     */
14223    public int getPaddingBottom() {
14224        return mPaddingBottom;
14225    }
14226
14227    /**
14228     * Returns the left padding of this view. If there are inset and enabled
14229     * scrollbars, this value may include the space required to display the
14230     * scrollbars as well.
14231     *
14232     * @return the left padding in pixels
14233     */
14234    public int getPaddingLeft() {
14235        return mPaddingLeft;
14236    }
14237
14238    /**
14239     * Returns the start padding of this view depending on its resolved layout direction.
14240     * If there are inset and enabled scrollbars, this value may include the space
14241     * required to display the scrollbars as well.
14242     *
14243     * @return the start padding in pixels
14244     */
14245    public int getPaddingStart() {
14246        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14247                mPaddingRight : mPaddingLeft;
14248    }
14249
14250    /**
14251     * Returns the right padding of this view. If there are inset and enabled
14252     * scrollbars, this value may include the space required to display the
14253     * scrollbars as well.
14254     *
14255     * @return the right padding in pixels
14256     */
14257    public int getPaddingRight() {
14258        return mPaddingRight;
14259    }
14260
14261    /**
14262     * Returns the end padding of this view depending on its resolved layout direction.
14263     * If there are inset and enabled scrollbars, this value may include the space
14264     * required to display the scrollbars as well.
14265     *
14266     * @return the end padding in pixels
14267     */
14268    public int getPaddingEnd() {
14269        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14270                mPaddingLeft : mPaddingRight;
14271    }
14272
14273    /**
14274     * Return if the padding as been set thru relative values
14275     * {@link #setPaddingRelative(int, int, int, int)} or thru
14276     * @attr ref android.R.styleable#View_paddingStart or
14277     * @attr ref android.R.styleable#View_paddingEnd
14278     *
14279     * @return true if the padding is relative or false if it is not.
14280     */
14281    public boolean isPaddingRelative() {
14282        return mUserPaddingRelative;
14283    }
14284
14285    /**
14286     * @hide
14287     */
14288    public Insets getOpticalInsets() {
14289        if (mLayoutInsets == null) {
14290            mLayoutInsets = (mBackground == null) ? Insets.NONE : mBackground.getLayoutInsets();
14291        }
14292        return mLayoutInsets;
14293    }
14294
14295    /**
14296     * @hide
14297     */
14298    public void setLayoutInsets(Insets layoutInsets) {
14299        mLayoutInsets = layoutInsets;
14300    }
14301
14302    /**
14303     * Changes the selection state of this view. A view can be selected or not.
14304     * Note that selection is not the same as focus. Views are typically
14305     * selected in the context of an AdapterView like ListView or GridView;
14306     * the selected view is the view that is highlighted.
14307     *
14308     * @param selected true if the view must be selected, false otherwise
14309     */
14310    public void setSelected(boolean selected) {
14311        if (((mPrivateFlags & SELECTED) != 0) != selected) {
14312            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
14313            if (!selected) resetPressedState();
14314            invalidate(true);
14315            refreshDrawableState();
14316            dispatchSetSelected(selected);
14317            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
14318                notifyAccessibilityStateChanged();
14319            }
14320        }
14321    }
14322
14323    /**
14324     * Dispatch setSelected to all of this View's children.
14325     *
14326     * @see #setSelected(boolean)
14327     *
14328     * @param selected The new selected state
14329     */
14330    protected void dispatchSetSelected(boolean selected) {
14331    }
14332
14333    /**
14334     * Indicates the selection state of this view.
14335     *
14336     * @return true if the view is selected, false otherwise
14337     */
14338    @ViewDebug.ExportedProperty
14339    public boolean isSelected() {
14340        return (mPrivateFlags & SELECTED) != 0;
14341    }
14342
14343    /**
14344     * Changes the activated state of this view. A view can be activated or not.
14345     * Note that activation is not the same as selection.  Selection is
14346     * a transient property, representing the view (hierarchy) the user is
14347     * currently interacting with.  Activation is a longer-term state that the
14348     * user can move views in and out of.  For example, in a list view with
14349     * single or multiple selection enabled, the views in the current selection
14350     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
14351     * here.)  The activated state is propagated down to children of the view it
14352     * is set on.
14353     *
14354     * @param activated true if the view must be activated, false otherwise
14355     */
14356    public void setActivated(boolean activated) {
14357        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
14358            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
14359            invalidate(true);
14360            refreshDrawableState();
14361            dispatchSetActivated(activated);
14362        }
14363    }
14364
14365    /**
14366     * Dispatch setActivated to all of this View's children.
14367     *
14368     * @see #setActivated(boolean)
14369     *
14370     * @param activated The new activated state
14371     */
14372    protected void dispatchSetActivated(boolean activated) {
14373    }
14374
14375    /**
14376     * Indicates the activation state of this view.
14377     *
14378     * @return true if the view is activated, false otherwise
14379     */
14380    @ViewDebug.ExportedProperty
14381    public boolean isActivated() {
14382        return (mPrivateFlags & ACTIVATED) != 0;
14383    }
14384
14385    /**
14386     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
14387     * observer can be used to get notifications when global events, like
14388     * layout, happen.
14389     *
14390     * The returned ViewTreeObserver observer is not guaranteed to remain
14391     * valid for the lifetime of this View. If the caller of this method keeps
14392     * a long-lived reference to ViewTreeObserver, it should always check for
14393     * the return value of {@link ViewTreeObserver#isAlive()}.
14394     *
14395     * @return The ViewTreeObserver for this view's hierarchy.
14396     */
14397    public ViewTreeObserver getViewTreeObserver() {
14398        if (mAttachInfo != null) {
14399            return mAttachInfo.mTreeObserver;
14400        }
14401        if (mFloatingTreeObserver == null) {
14402            mFloatingTreeObserver = new ViewTreeObserver();
14403        }
14404        return mFloatingTreeObserver;
14405    }
14406
14407    /**
14408     * <p>Finds the topmost view in the current view hierarchy.</p>
14409     *
14410     * @return the topmost view containing this view
14411     */
14412    public View getRootView() {
14413        if (mAttachInfo != null) {
14414            final View v = mAttachInfo.mRootView;
14415            if (v != null) {
14416                return v;
14417            }
14418        }
14419
14420        View parent = this;
14421
14422        while (parent.mParent != null && parent.mParent instanceof View) {
14423            parent = (View) parent.mParent;
14424        }
14425
14426        return parent;
14427    }
14428
14429    /**
14430     * <p>Computes the coordinates of this view on the screen. The argument
14431     * must be an array of two integers. After the method returns, the array
14432     * contains the x and y location in that order.</p>
14433     *
14434     * @param location an array of two integers in which to hold the coordinates
14435     */
14436    public void getLocationOnScreen(int[] location) {
14437        getLocationInWindow(location);
14438
14439        final AttachInfo info = mAttachInfo;
14440        if (info != null) {
14441            location[0] += info.mWindowLeft;
14442            location[1] += info.mWindowTop;
14443        }
14444    }
14445
14446    /**
14447     * <p>Computes the coordinates of this view in its window. The argument
14448     * must be an array of two integers. After the method returns, the array
14449     * contains the x and y location in that order.</p>
14450     *
14451     * @param location an array of two integers in which to hold the coordinates
14452     */
14453    public void getLocationInWindow(int[] location) {
14454        if (location == null || location.length < 2) {
14455            throw new IllegalArgumentException("location must be an array of two integers");
14456        }
14457
14458        if (mAttachInfo == null) {
14459            // When the view is not attached to a window, this method does not make sense
14460            location[0] = location[1] = 0;
14461            return;
14462        }
14463
14464        float[] position = mAttachInfo.mTmpTransformLocation;
14465        position[0] = position[1] = 0.0f;
14466
14467        if (!hasIdentityMatrix()) {
14468            getMatrix().mapPoints(position);
14469        }
14470
14471        position[0] += mLeft;
14472        position[1] += mTop;
14473
14474        ViewParent viewParent = mParent;
14475        while (viewParent instanceof View) {
14476            final View view = (View) viewParent;
14477
14478            position[0] -= view.mScrollX;
14479            position[1] -= view.mScrollY;
14480
14481            if (!view.hasIdentityMatrix()) {
14482                view.getMatrix().mapPoints(position);
14483            }
14484
14485            position[0] += view.mLeft;
14486            position[1] += view.mTop;
14487
14488            viewParent = view.mParent;
14489         }
14490
14491        if (viewParent instanceof ViewRootImpl) {
14492            // *cough*
14493            final ViewRootImpl vr = (ViewRootImpl) viewParent;
14494            position[1] -= vr.mCurScrollY;
14495        }
14496
14497        location[0] = (int) (position[0] + 0.5f);
14498        location[1] = (int) (position[1] + 0.5f);
14499    }
14500
14501    /**
14502     * {@hide}
14503     * @param id the id of the view to be found
14504     * @return the view of the specified id, null if cannot be found
14505     */
14506    protected View findViewTraversal(int id) {
14507        if (id == mID) {
14508            return this;
14509        }
14510        return null;
14511    }
14512
14513    /**
14514     * {@hide}
14515     * @param tag the tag of the view to be found
14516     * @return the view of specified tag, null if cannot be found
14517     */
14518    protected View findViewWithTagTraversal(Object tag) {
14519        if (tag != null && tag.equals(mTag)) {
14520            return this;
14521        }
14522        return null;
14523    }
14524
14525    /**
14526     * {@hide}
14527     * @param predicate The predicate to evaluate.
14528     * @param childToSkip If not null, ignores this child during the recursive traversal.
14529     * @return The first view that matches the predicate or null.
14530     */
14531    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
14532        if (predicate.apply(this)) {
14533            return this;
14534        }
14535        return null;
14536    }
14537
14538    /**
14539     * Look for a child view with the given id.  If this view has the given
14540     * id, return this view.
14541     *
14542     * @param id The id to search for.
14543     * @return The view that has the given id in the hierarchy or null
14544     */
14545    public final View findViewById(int id) {
14546        if (id < 0) {
14547            return null;
14548        }
14549        return findViewTraversal(id);
14550    }
14551
14552    /**
14553     * Finds a view by its unuque and stable accessibility id.
14554     *
14555     * @param accessibilityId The searched accessibility id.
14556     * @return The found view.
14557     */
14558    final View findViewByAccessibilityId(int accessibilityId) {
14559        if (accessibilityId < 0) {
14560            return null;
14561        }
14562        return findViewByAccessibilityIdTraversal(accessibilityId);
14563    }
14564
14565    /**
14566     * Performs the traversal to find a view by its unuque and stable accessibility id.
14567     *
14568     * <strong>Note:</strong>This method does not stop at the root namespace
14569     * boundary since the user can touch the screen at an arbitrary location
14570     * potentially crossing the root namespace bounday which will send an
14571     * accessibility event to accessibility services and they should be able
14572     * to obtain the event source. Also accessibility ids are guaranteed to be
14573     * unique in the window.
14574     *
14575     * @param accessibilityId The accessibility id.
14576     * @return The found view.
14577     */
14578    View findViewByAccessibilityIdTraversal(int accessibilityId) {
14579        if (getAccessibilityViewId() == accessibilityId) {
14580            return this;
14581        }
14582        return null;
14583    }
14584
14585    /**
14586     * Look for a child view with the given tag.  If this view has the given
14587     * tag, return this view.
14588     *
14589     * @param tag The tag to search for, using "tag.equals(getTag())".
14590     * @return The View that has the given tag in the hierarchy or null
14591     */
14592    public final View findViewWithTag(Object tag) {
14593        if (tag == null) {
14594            return null;
14595        }
14596        return findViewWithTagTraversal(tag);
14597    }
14598
14599    /**
14600     * {@hide}
14601     * Look for a child view that matches the specified predicate.
14602     * If this view matches the predicate, return this view.
14603     *
14604     * @param predicate The predicate to evaluate.
14605     * @return The first view that matches the predicate or null.
14606     */
14607    public final View findViewByPredicate(Predicate<View> predicate) {
14608        return findViewByPredicateTraversal(predicate, null);
14609    }
14610
14611    /**
14612     * {@hide}
14613     * Look for a child view that matches the specified predicate,
14614     * starting with the specified view and its descendents and then
14615     * recusively searching the ancestors and siblings of that view
14616     * until this view is reached.
14617     *
14618     * This method is useful in cases where the predicate does not match
14619     * a single unique view (perhaps multiple views use the same id)
14620     * and we are trying to find the view that is "closest" in scope to the
14621     * starting view.
14622     *
14623     * @param start The view to start from.
14624     * @param predicate The predicate to evaluate.
14625     * @return The first view that matches the predicate or null.
14626     */
14627    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
14628        View childToSkip = null;
14629        for (;;) {
14630            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
14631            if (view != null || start == this) {
14632                return view;
14633            }
14634
14635            ViewParent parent = start.getParent();
14636            if (parent == null || !(parent instanceof View)) {
14637                return null;
14638            }
14639
14640            childToSkip = start;
14641            start = (View) parent;
14642        }
14643    }
14644
14645    /**
14646     * Sets the identifier for this view. The identifier does not have to be
14647     * unique in this view's hierarchy. The identifier should be a positive
14648     * number.
14649     *
14650     * @see #NO_ID
14651     * @see #getId()
14652     * @see #findViewById(int)
14653     *
14654     * @param id a number used to identify the view
14655     *
14656     * @attr ref android.R.styleable#View_id
14657     */
14658    public void setId(int id) {
14659        mID = id;
14660    }
14661
14662    /**
14663     * {@hide}
14664     *
14665     * @param isRoot true if the view belongs to the root namespace, false
14666     *        otherwise
14667     */
14668    public void setIsRootNamespace(boolean isRoot) {
14669        if (isRoot) {
14670            mPrivateFlags |= IS_ROOT_NAMESPACE;
14671        } else {
14672            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
14673        }
14674    }
14675
14676    /**
14677     * {@hide}
14678     *
14679     * @return true if the view belongs to the root namespace, false otherwise
14680     */
14681    public boolean isRootNamespace() {
14682        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
14683    }
14684
14685    /**
14686     * Returns this view's identifier.
14687     *
14688     * @return a positive integer used to identify the view or {@link #NO_ID}
14689     *         if the view has no ID
14690     *
14691     * @see #setId(int)
14692     * @see #findViewById(int)
14693     * @attr ref android.R.styleable#View_id
14694     */
14695    @ViewDebug.CapturedViewProperty
14696    public int getId() {
14697        return mID;
14698    }
14699
14700    /**
14701     * Returns this view's tag.
14702     *
14703     * @return the Object stored in this view as a tag
14704     *
14705     * @see #setTag(Object)
14706     * @see #getTag(int)
14707     */
14708    @ViewDebug.ExportedProperty
14709    public Object getTag() {
14710        return mTag;
14711    }
14712
14713    /**
14714     * Sets the tag associated with this view. A tag can be used to mark
14715     * a view in its hierarchy and does not have to be unique within the
14716     * hierarchy. Tags can also be used to store data within a view without
14717     * resorting to another data structure.
14718     *
14719     * @param tag an Object to tag the view with
14720     *
14721     * @see #getTag()
14722     * @see #setTag(int, Object)
14723     */
14724    public void setTag(final Object tag) {
14725        mTag = tag;
14726    }
14727
14728    /**
14729     * Returns the tag associated with this view and the specified key.
14730     *
14731     * @param key The key identifying the tag
14732     *
14733     * @return the Object stored in this view as a tag
14734     *
14735     * @see #setTag(int, Object)
14736     * @see #getTag()
14737     */
14738    public Object getTag(int key) {
14739        if (mKeyedTags != null) return mKeyedTags.get(key);
14740        return null;
14741    }
14742
14743    /**
14744     * Sets a tag associated with this view and a key. A tag can be used
14745     * to mark a view in its hierarchy and does not have to be unique within
14746     * the hierarchy. Tags can also be used to store data within a view
14747     * without resorting to another data structure.
14748     *
14749     * The specified key should be an id declared in the resources of the
14750     * application to ensure it is unique (see the <a
14751     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
14752     * Keys identified as belonging to
14753     * the Android framework or not associated with any package will cause
14754     * an {@link IllegalArgumentException} to be thrown.
14755     *
14756     * @param key The key identifying the tag
14757     * @param tag An Object to tag the view with
14758     *
14759     * @throws IllegalArgumentException If they specified key is not valid
14760     *
14761     * @see #setTag(Object)
14762     * @see #getTag(int)
14763     */
14764    public void setTag(int key, final Object tag) {
14765        // If the package id is 0x00 or 0x01, it's either an undefined package
14766        // or a framework id
14767        if ((key >>> 24) < 2) {
14768            throw new IllegalArgumentException("The key must be an application-specific "
14769                    + "resource id.");
14770        }
14771
14772        setKeyedTag(key, tag);
14773    }
14774
14775    /**
14776     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
14777     * framework id.
14778     *
14779     * @hide
14780     */
14781    public void setTagInternal(int key, Object tag) {
14782        if ((key >>> 24) != 0x1) {
14783            throw new IllegalArgumentException("The key must be a framework-specific "
14784                    + "resource id.");
14785        }
14786
14787        setKeyedTag(key, tag);
14788    }
14789
14790    private void setKeyedTag(int key, Object tag) {
14791        if (mKeyedTags == null) {
14792            mKeyedTags = new SparseArray<Object>();
14793        }
14794
14795        mKeyedTags.put(key, tag);
14796    }
14797
14798    /**
14799     * Prints information about this view in the log output, with the tag
14800     * {@link #VIEW_LOG_TAG}.
14801     *
14802     * @hide
14803     */
14804    public void debug() {
14805        debug(0);
14806    }
14807
14808    /**
14809     * Prints information about this view in the log output, with the tag
14810     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
14811     * indentation defined by the <code>depth</code>.
14812     *
14813     * @param depth the indentation level
14814     *
14815     * @hide
14816     */
14817    protected void debug(int depth) {
14818        String output = debugIndent(depth - 1);
14819
14820        output += "+ " + this;
14821        int id = getId();
14822        if (id != -1) {
14823            output += " (id=" + id + ")";
14824        }
14825        Object tag = getTag();
14826        if (tag != null) {
14827            output += " (tag=" + tag + ")";
14828        }
14829        Log.d(VIEW_LOG_TAG, output);
14830
14831        if ((mPrivateFlags & FOCUSED) != 0) {
14832            output = debugIndent(depth) + " FOCUSED";
14833            Log.d(VIEW_LOG_TAG, output);
14834        }
14835
14836        output = debugIndent(depth);
14837        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
14838                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
14839                + "} ";
14840        Log.d(VIEW_LOG_TAG, output);
14841
14842        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
14843                || mPaddingBottom != 0) {
14844            output = debugIndent(depth);
14845            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
14846                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
14847            Log.d(VIEW_LOG_TAG, output);
14848        }
14849
14850        output = debugIndent(depth);
14851        output += "mMeasureWidth=" + mMeasuredWidth +
14852                " mMeasureHeight=" + mMeasuredHeight;
14853        Log.d(VIEW_LOG_TAG, output);
14854
14855        output = debugIndent(depth);
14856        if (mLayoutParams == null) {
14857            output += "BAD! no layout params";
14858        } else {
14859            output = mLayoutParams.debug(output);
14860        }
14861        Log.d(VIEW_LOG_TAG, output);
14862
14863        output = debugIndent(depth);
14864        output += "flags={";
14865        output += View.printFlags(mViewFlags);
14866        output += "}";
14867        Log.d(VIEW_LOG_TAG, output);
14868
14869        output = debugIndent(depth);
14870        output += "privateFlags={";
14871        output += View.printPrivateFlags(mPrivateFlags);
14872        output += "}";
14873        Log.d(VIEW_LOG_TAG, output);
14874    }
14875
14876    /**
14877     * Creates a string of whitespaces used for indentation.
14878     *
14879     * @param depth the indentation level
14880     * @return a String containing (depth * 2 + 3) * 2 white spaces
14881     *
14882     * @hide
14883     */
14884    protected static String debugIndent(int depth) {
14885        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
14886        for (int i = 0; i < (depth * 2) + 3; i++) {
14887            spaces.append(' ').append(' ');
14888        }
14889        return spaces.toString();
14890    }
14891
14892    /**
14893     * <p>Return the offset of the widget's text baseline from the widget's top
14894     * boundary. If this widget does not support baseline alignment, this
14895     * method returns -1. </p>
14896     *
14897     * @return the offset of the baseline within the widget's bounds or -1
14898     *         if baseline alignment is not supported
14899     */
14900    @ViewDebug.ExportedProperty(category = "layout")
14901    public int getBaseline() {
14902        return -1;
14903    }
14904
14905    /**
14906     * Call this when something has changed which has invalidated the
14907     * layout of this view. This will schedule a layout pass of the view
14908     * tree.
14909     */
14910    public void requestLayout() {
14911        mPrivateFlags |= FORCE_LAYOUT;
14912        mPrivateFlags |= INVALIDATED;
14913
14914        if (mLayoutParams != null) {
14915            mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
14916        }
14917
14918        if (mParent != null && !mParent.isLayoutRequested()) {
14919            mParent.requestLayout();
14920        }
14921    }
14922
14923    /**
14924     * Forces this view to be laid out during the next layout pass.
14925     * This method does not call requestLayout() or forceLayout()
14926     * on the parent.
14927     */
14928    public void forceLayout() {
14929        mPrivateFlags |= FORCE_LAYOUT;
14930        mPrivateFlags |= INVALIDATED;
14931    }
14932
14933    /**
14934     * <p>
14935     * This is called to find out how big a view should be. The parent
14936     * supplies constraint information in the width and height parameters.
14937     * </p>
14938     *
14939     * <p>
14940     * The actual measurement work of a view is performed in
14941     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
14942     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
14943     * </p>
14944     *
14945     *
14946     * @param widthMeasureSpec Horizontal space requirements as imposed by the
14947     *        parent
14948     * @param heightMeasureSpec Vertical space requirements as imposed by the
14949     *        parent
14950     *
14951     * @see #onMeasure(int, int)
14952     */
14953    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
14954        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
14955                widthMeasureSpec != mOldWidthMeasureSpec ||
14956                heightMeasureSpec != mOldHeightMeasureSpec) {
14957
14958            // first clears the measured dimension flag
14959            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
14960
14961            // measure ourselves, this should set the measured dimension flag back
14962            onMeasure(widthMeasureSpec, heightMeasureSpec);
14963
14964            // flag not set, setMeasuredDimension() was not invoked, we raise
14965            // an exception to warn the developer
14966            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
14967                throw new IllegalStateException("onMeasure() did not set the"
14968                        + " measured dimension by calling"
14969                        + " setMeasuredDimension()");
14970            }
14971
14972            mPrivateFlags |= LAYOUT_REQUIRED;
14973        }
14974
14975        mOldWidthMeasureSpec = widthMeasureSpec;
14976        mOldHeightMeasureSpec = heightMeasureSpec;
14977    }
14978
14979    /**
14980     * <p>
14981     * Measure the view and its content to determine the measured width and the
14982     * measured height. This method is invoked by {@link #measure(int, int)} and
14983     * should be overriden by subclasses to provide accurate and efficient
14984     * measurement of their contents.
14985     * </p>
14986     *
14987     * <p>
14988     * <strong>CONTRACT:</strong> When overriding this method, you
14989     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
14990     * measured width and height of this view. Failure to do so will trigger an
14991     * <code>IllegalStateException</code>, thrown by
14992     * {@link #measure(int, int)}. Calling the superclass'
14993     * {@link #onMeasure(int, int)} is a valid use.
14994     * </p>
14995     *
14996     * <p>
14997     * The base class implementation of measure defaults to the background size,
14998     * unless a larger size is allowed by the MeasureSpec. Subclasses should
14999     * override {@link #onMeasure(int, int)} to provide better measurements of
15000     * their content.
15001     * </p>
15002     *
15003     * <p>
15004     * If this method is overridden, it is the subclass's responsibility to make
15005     * sure the measured height and width are at least the view's minimum height
15006     * and width ({@link #getSuggestedMinimumHeight()} and
15007     * {@link #getSuggestedMinimumWidth()}).
15008     * </p>
15009     *
15010     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15011     *                         The requirements are encoded with
15012     *                         {@link android.view.View.MeasureSpec}.
15013     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15014     *                         The requirements are encoded with
15015     *                         {@link android.view.View.MeasureSpec}.
15016     *
15017     * @see #getMeasuredWidth()
15018     * @see #getMeasuredHeight()
15019     * @see #setMeasuredDimension(int, int)
15020     * @see #getSuggestedMinimumHeight()
15021     * @see #getSuggestedMinimumWidth()
15022     * @see android.view.View.MeasureSpec#getMode(int)
15023     * @see android.view.View.MeasureSpec#getSize(int)
15024     */
15025    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15026        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15027                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15028    }
15029
15030    /**
15031     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15032     * measured width and measured height. Failing to do so will trigger an
15033     * exception at measurement time.</p>
15034     *
15035     * @param measuredWidth The measured width of this view.  May be a complex
15036     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15037     * {@link #MEASURED_STATE_TOO_SMALL}.
15038     * @param measuredHeight The measured height of this view.  May be a complex
15039     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15040     * {@link #MEASURED_STATE_TOO_SMALL}.
15041     */
15042    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15043        mMeasuredWidth = measuredWidth;
15044        mMeasuredHeight = measuredHeight;
15045
15046        mPrivateFlags |= MEASURED_DIMENSION_SET;
15047    }
15048
15049    /**
15050     * Merge two states as returned by {@link #getMeasuredState()}.
15051     * @param curState The current state as returned from a view or the result
15052     * of combining multiple views.
15053     * @param newState The new view state to combine.
15054     * @return Returns a new integer reflecting the combination of the two
15055     * states.
15056     */
15057    public static int combineMeasuredStates(int curState, int newState) {
15058        return curState | newState;
15059    }
15060
15061    /**
15062     * Version of {@link #resolveSizeAndState(int, int, int)}
15063     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15064     */
15065    public static int resolveSize(int size, int measureSpec) {
15066        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15067    }
15068
15069    /**
15070     * Utility to reconcile a desired size and state, with constraints imposed
15071     * by a MeasureSpec.  Will take the desired size, unless a different size
15072     * is imposed by the constraints.  The returned value is a compound integer,
15073     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15074     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15075     * size is smaller than the size the view wants to be.
15076     *
15077     * @param size How big the view wants to be
15078     * @param measureSpec Constraints imposed by the parent
15079     * @return Size information bit mask as defined by
15080     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15081     */
15082    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15083        int result = size;
15084        int specMode = MeasureSpec.getMode(measureSpec);
15085        int specSize =  MeasureSpec.getSize(measureSpec);
15086        switch (specMode) {
15087        case MeasureSpec.UNSPECIFIED:
15088            result = size;
15089            break;
15090        case MeasureSpec.AT_MOST:
15091            if (specSize < size) {
15092                result = specSize | MEASURED_STATE_TOO_SMALL;
15093            } else {
15094                result = size;
15095            }
15096            break;
15097        case MeasureSpec.EXACTLY:
15098            result = specSize;
15099            break;
15100        }
15101        return result | (childMeasuredState&MEASURED_STATE_MASK);
15102    }
15103
15104    /**
15105     * Utility to return a default size. Uses the supplied size if the
15106     * MeasureSpec imposed no constraints. Will get larger if allowed
15107     * by the MeasureSpec.
15108     *
15109     * @param size Default size for this view
15110     * @param measureSpec Constraints imposed by the parent
15111     * @return The size this view should be.
15112     */
15113    public static int getDefaultSize(int size, int measureSpec) {
15114        int result = size;
15115        int specMode = MeasureSpec.getMode(measureSpec);
15116        int specSize = MeasureSpec.getSize(measureSpec);
15117
15118        switch (specMode) {
15119        case MeasureSpec.UNSPECIFIED:
15120            result = size;
15121            break;
15122        case MeasureSpec.AT_MOST:
15123        case MeasureSpec.EXACTLY:
15124            result = specSize;
15125            break;
15126        }
15127        return result;
15128    }
15129
15130    /**
15131     * Returns the suggested minimum height that the view should use. This
15132     * returns the maximum of the view's minimum height
15133     * and the background's minimum height
15134     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15135     * <p>
15136     * When being used in {@link #onMeasure(int, int)}, the caller should still
15137     * ensure the returned height is within the requirements of the parent.
15138     *
15139     * @return The suggested minimum height of the view.
15140     */
15141    protected int getSuggestedMinimumHeight() {
15142        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15143
15144    }
15145
15146    /**
15147     * Returns the suggested minimum width that the view should use. This
15148     * returns the maximum of the view's minimum width)
15149     * and the background's minimum width
15150     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15151     * <p>
15152     * When being used in {@link #onMeasure(int, int)}, the caller should still
15153     * ensure the returned width is within the requirements of the parent.
15154     *
15155     * @return The suggested minimum width of the view.
15156     */
15157    protected int getSuggestedMinimumWidth() {
15158        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15159    }
15160
15161    /**
15162     * Returns the minimum height of the view.
15163     *
15164     * @return the minimum height the view will try to be.
15165     *
15166     * @see #setMinimumHeight(int)
15167     *
15168     * @attr ref android.R.styleable#View_minHeight
15169     */
15170    public int getMinimumHeight() {
15171        return mMinHeight;
15172    }
15173
15174    /**
15175     * Sets the minimum height of the view. It is not guaranteed the view will
15176     * be able to achieve this minimum height (for example, if its parent layout
15177     * constrains it with less available height).
15178     *
15179     * @param minHeight The minimum height the view will try to be.
15180     *
15181     * @see #getMinimumHeight()
15182     *
15183     * @attr ref android.R.styleable#View_minHeight
15184     */
15185    public void setMinimumHeight(int minHeight) {
15186        mMinHeight = minHeight;
15187        requestLayout();
15188    }
15189
15190    /**
15191     * Returns the minimum width of the view.
15192     *
15193     * @return the minimum width the view will try to be.
15194     *
15195     * @see #setMinimumWidth(int)
15196     *
15197     * @attr ref android.R.styleable#View_minWidth
15198     */
15199    public int getMinimumWidth() {
15200        return mMinWidth;
15201    }
15202
15203    /**
15204     * Sets the minimum width of the view. It is not guaranteed the view will
15205     * be able to achieve this minimum width (for example, if its parent layout
15206     * constrains it with less available width).
15207     *
15208     * @param minWidth The minimum width the view will try to be.
15209     *
15210     * @see #getMinimumWidth()
15211     *
15212     * @attr ref android.R.styleable#View_minWidth
15213     */
15214    public void setMinimumWidth(int minWidth) {
15215        mMinWidth = minWidth;
15216        requestLayout();
15217
15218    }
15219
15220    /**
15221     * Get the animation currently associated with this view.
15222     *
15223     * @return The animation that is currently playing or
15224     *         scheduled to play for this view.
15225     */
15226    public Animation getAnimation() {
15227        return mCurrentAnimation;
15228    }
15229
15230    /**
15231     * Start the specified animation now.
15232     *
15233     * @param animation the animation to start now
15234     */
15235    public void startAnimation(Animation animation) {
15236        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
15237        setAnimation(animation);
15238        invalidateParentCaches();
15239        invalidate(true);
15240    }
15241
15242    /**
15243     * Cancels any animations for this view.
15244     */
15245    public void clearAnimation() {
15246        if (mCurrentAnimation != null) {
15247            mCurrentAnimation.detach();
15248        }
15249        mCurrentAnimation = null;
15250        invalidateParentIfNeeded();
15251    }
15252
15253    /**
15254     * Sets the next animation to play for this view.
15255     * If you want the animation to play immediately, use
15256     * {@link #startAnimation(android.view.animation.Animation)} instead.
15257     * This method provides allows fine-grained
15258     * control over the start time and invalidation, but you
15259     * must make sure that 1) the animation has a start time set, and
15260     * 2) the view's parent (which controls animations on its children)
15261     * will be invalidated when the animation is supposed to
15262     * start.
15263     *
15264     * @param animation The next animation, or null.
15265     */
15266    public void setAnimation(Animation animation) {
15267        mCurrentAnimation = animation;
15268
15269        if (animation != null) {
15270            // If the screen is off assume the animation start time is now instead of
15271            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
15272            // would cause the animation to start when the screen turns back on
15273            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
15274                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
15275                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
15276            }
15277            animation.reset();
15278        }
15279    }
15280
15281    /**
15282     * Invoked by a parent ViewGroup to notify the start of the animation
15283     * currently associated with this view. If you override this method,
15284     * always call super.onAnimationStart();
15285     *
15286     * @see #setAnimation(android.view.animation.Animation)
15287     * @see #getAnimation()
15288     */
15289    protected void onAnimationStart() {
15290        mPrivateFlags |= ANIMATION_STARTED;
15291    }
15292
15293    /**
15294     * Invoked by a parent ViewGroup to notify the end of the animation
15295     * currently associated with this view. If you override this method,
15296     * always call super.onAnimationEnd();
15297     *
15298     * @see #setAnimation(android.view.animation.Animation)
15299     * @see #getAnimation()
15300     */
15301    protected void onAnimationEnd() {
15302        mPrivateFlags &= ~ANIMATION_STARTED;
15303    }
15304
15305    /**
15306     * Invoked if there is a Transform that involves alpha. Subclass that can
15307     * draw themselves with the specified alpha should return true, and then
15308     * respect that alpha when their onDraw() is called. If this returns false
15309     * then the view may be redirected to draw into an offscreen buffer to
15310     * fulfill the request, which will look fine, but may be slower than if the
15311     * subclass handles it internally. The default implementation returns false.
15312     *
15313     * @param alpha The alpha (0..255) to apply to the view's drawing
15314     * @return true if the view can draw with the specified alpha.
15315     */
15316    protected boolean onSetAlpha(int alpha) {
15317        return false;
15318    }
15319
15320    /**
15321     * This is used by the RootView to perform an optimization when
15322     * the view hierarchy contains one or several SurfaceView.
15323     * SurfaceView is always considered transparent, but its children are not,
15324     * therefore all View objects remove themselves from the global transparent
15325     * region (passed as a parameter to this function).
15326     *
15327     * @param region The transparent region for this ViewAncestor (window).
15328     *
15329     * @return Returns true if the effective visibility of the view at this
15330     * point is opaque, regardless of the transparent region; returns false
15331     * if it is possible for underlying windows to be seen behind the view.
15332     *
15333     * {@hide}
15334     */
15335    public boolean gatherTransparentRegion(Region region) {
15336        final AttachInfo attachInfo = mAttachInfo;
15337        if (region != null && attachInfo != null) {
15338            final int pflags = mPrivateFlags;
15339            if ((pflags & SKIP_DRAW) == 0) {
15340                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
15341                // remove it from the transparent region.
15342                final int[] location = attachInfo.mTransparentLocation;
15343                getLocationInWindow(location);
15344                region.op(location[0], location[1], location[0] + mRight - mLeft,
15345                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
15346            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
15347                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
15348                // exists, so we remove the background drawable's non-transparent
15349                // parts from this transparent region.
15350                applyDrawableToTransparentRegion(mBackground, region);
15351            }
15352        }
15353        return true;
15354    }
15355
15356    /**
15357     * Play a sound effect for this view.
15358     *
15359     * <p>The framework will play sound effects for some built in actions, such as
15360     * clicking, but you may wish to play these effects in your widget,
15361     * for instance, for internal navigation.
15362     *
15363     * <p>The sound effect will only be played if sound effects are enabled by the user, and
15364     * {@link #isSoundEffectsEnabled()} is true.
15365     *
15366     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
15367     */
15368    public void playSoundEffect(int soundConstant) {
15369        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
15370            return;
15371        }
15372        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
15373    }
15374
15375    /**
15376     * BZZZTT!!1!
15377     *
15378     * <p>Provide haptic feedback to the user for this view.
15379     *
15380     * <p>The framework will provide haptic feedback for some built in actions,
15381     * such as long presses, but you may wish to provide feedback for your
15382     * own widget.
15383     *
15384     * <p>The feedback will only be performed if
15385     * {@link #isHapticFeedbackEnabled()} is true.
15386     *
15387     * @param feedbackConstant One of the constants defined in
15388     * {@link HapticFeedbackConstants}
15389     */
15390    public boolean performHapticFeedback(int feedbackConstant) {
15391        return performHapticFeedback(feedbackConstant, 0);
15392    }
15393
15394    /**
15395     * BZZZTT!!1!
15396     *
15397     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
15398     *
15399     * @param feedbackConstant One of the constants defined in
15400     * {@link HapticFeedbackConstants}
15401     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
15402     */
15403    public boolean performHapticFeedback(int feedbackConstant, int flags) {
15404        if (mAttachInfo == null) {
15405            return false;
15406        }
15407        //noinspection SimplifiableIfStatement
15408        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
15409                && !isHapticFeedbackEnabled()) {
15410            return false;
15411        }
15412        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
15413                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
15414    }
15415
15416    /**
15417     * Request that the visibility of the status bar or other screen/window
15418     * decorations be changed.
15419     *
15420     * <p>This method is used to put the over device UI into temporary modes
15421     * where the user's attention is focused more on the application content,
15422     * by dimming or hiding surrounding system affordances.  This is typically
15423     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
15424     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
15425     * to be placed behind the action bar (and with these flags other system
15426     * affordances) so that smooth transitions between hiding and showing them
15427     * can be done.
15428     *
15429     * <p>Two representative examples of the use of system UI visibility is
15430     * implementing a content browsing application (like a magazine reader)
15431     * and a video playing application.
15432     *
15433     * <p>The first code shows a typical implementation of a View in a content
15434     * browsing application.  In this implementation, the application goes
15435     * into a content-oriented mode by hiding the status bar and action bar,
15436     * and putting the navigation elements into lights out mode.  The user can
15437     * then interact with content while in this mode.  Such an application should
15438     * provide an easy way for the user to toggle out of the mode (such as to
15439     * check information in the status bar or access notifications).  In the
15440     * implementation here, this is done simply by tapping on the content.
15441     *
15442     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
15443     *      content}
15444     *
15445     * <p>This second code sample shows a typical implementation of a View
15446     * in a video playing application.  In this situation, while the video is
15447     * playing the application would like to go into a complete full-screen mode,
15448     * to use as much of the display as possible for the video.  When in this state
15449     * the user can not interact with the application; the system intercepts
15450     * touching on the screen to pop the UI out of full screen mode.  See
15451     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
15452     *
15453     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
15454     *      content}
15455     *
15456     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15457     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15458     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15459     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15460     */
15461    public void setSystemUiVisibility(int visibility) {
15462        if (visibility != mSystemUiVisibility) {
15463            mSystemUiVisibility = visibility;
15464            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15465                mParent.recomputeViewAttributes(this);
15466            }
15467        }
15468    }
15469
15470    /**
15471     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
15472     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
15473     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
15474     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
15475     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
15476     */
15477    public int getSystemUiVisibility() {
15478        return mSystemUiVisibility;
15479    }
15480
15481    /**
15482     * Returns the current system UI visibility that is currently set for
15483     * the entire window.  This is the combination of the
15484     * {@link #setSystemUiVisibility(int)} values supplied by all of the
15485     * views in the window.
15486     */
15487    public int getWindowSystemUiVisibility() {
15488        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
15489    }
15490
15491    /**
15492     * Override to find out when the window's requested system UI visibility
15493     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
15494     * This is different from the callbacks recieved through
15495     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
15496     * in that this is only telling you about the local request of the window,
15497     * not the actual values applied by the system.
15498     */
15499    public void onWindowSystemUiVisibilityChanged(int visible) {
15500    }
15501
15502    /**
15503     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
15504     * the view hierarchy.
15505     */
15506    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
15507        onWindowSystemUiVisibilityChanged(visible);
15508    }
15509
15510    /**
15511     * Set a listener to receive callbacks when the visibility of the system bar changes.
15512     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
15513     */
15514    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
15515        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
15516        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
15517            mParent.recomputeViewAttributes(this);
15518        }
15519    }
15520
15521    /**
15522     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
15523     * the view hierarchy.
15524     */
15525    public void dispatchSystemUiVisibilityChanged(int visibility) {
15526        ListenerInfo li = mListenerInfo;
15527        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
15528            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
15529                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
15530        }
15531    }
15532
15533    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
15534        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
15535        if (val != mSystemUiVisibility) {
15536            setSystemUiVisibility(val);
15537            return true;
15538        }
15539        return false;
15540    }
15541
15542    /** @hide */
15543    public void setDisabledSystemUiVisibility(int flags) {
15544        if (mAttachInfo != null) {
15545            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
15546                mAttachInfo.mDisabledSystemUiVisibility = flags;
15547                if (mParent != null) {
15548                    mParent.recomputeViewAttributes(this);
15549                }
15550            }
15551        }
15552    }
15553
15554    /**
15555     * Creates an image that the system displays during the drag and drop
15556     * operation. This is called a &quot;drag shadow&quot;. The default implementation
15557     * for a DragShadowBuilder based on a View returns an image that has exactly the same
15558     * appearance as the given View. The default also positions the center of the drag shadow
15559     * directly under the touch point. If no View is provided (the constructor with no parameters
15560     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
15561     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
15562     * default is an invisible drag shadow.
15563     * <p>
15564     * You are not required to use the View you provide to the constructor as the basis of the
15565     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
15566     * anything you want as the drag shadow.
15567     * </p>
15568     * <p>
15569     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
15570     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
15571     *  size and position of the drag shadow. It uses this data to construct a
15572     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
15573     *  so that your application can draw the shadow image in the Canvas.
15574     * </p>
15575     *
15576     * <div class="special reference">
15577     * <h3>Developer Guides</h3>
15578     * <p>For a guide to implementing drag and drop features, read the
15579     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
15580     * </div>
15581     */
15582    public static class DragShadowBuilder {
15583        private final WeakReference<View> mView;
15584
15585        /**
15586         * Constructs a shadow image builder based on a View. By default, the resulting drag
15587         * shadow will have the same appearance and dimensions as the View, with the touch point
15588         * over the center of the View.
15589         * @param view A View. Any View in scope can be used.
15590         */
15591        public DragShadowBuilder(View view) {
15592            mView = new WeakReference<View>(view);
15593        }
15594
15595        /**
15596         * Construct a shadow builder object with no associated View.  This
15597         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
15598         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
15599         * to supply the drag shadow's dimensions and appearance without
15600         * reference to any View object. If they are not overridden, then the result is an
15601         * invisible drag shadow.
15602         */
15603        public DragShadowBuilder() {
15604            mView = new WeakReference<View>(null);
15605        }
15606
15607        /**
15608         * Returns the View object that had been passed to the
15609         * {@link #View.DragShadowBuilder(View)}
15610         * constructor.  If that View parameter was {@code null} or if the
15611         * {@link #View.DragShadowBuilder()}
15612         * constructor was used to instantiate the builder object, this method will return
15613         * null.
15614         *
15615         * @return The View object associate with this builder object.
15616         */
15617        @SuppressWarnings({"JavadocReference"})
15618        final public View getView() {
15619            return mView.get();
15620        }
15621
15622        /**
15623         * Provides the metrics for the shadow image. These include the dimensions of
15624         * the shadow image, and the point within that shadow that should
15625         * be centered under the touch location while dragging.
15626         * <p>
15627         * The default implementation sets the dimensions of the shadow to be the
15628         * same as the dimensions of the View itself and centers the shadow under
15629         * the touch point.
15630         * </p>
15631         *
15632         * @param shadowSize A {@link android.graphics.Point} containing the width and height
15633         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
15634         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
15635         * image.
15636         *
15637         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
15638         * shadow image that should be underneath the touch point during the drag and drop
15639         * operation. Your application must set {@link android.graphics.Point#x} to the
15640         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
15641         */
15642        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
15643            final View view = mView.get();
15644            if (view != null) {
15645                shadowSize.set(view.getWidth(), view.getHeight());
15646                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
15647            } else {
15648                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
15649            }
15650        }
15651
15652        /**
15653         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
15654         * based on the dimensions it received from the
15655         * {@link #onProvideShadowMetrics(Point, Point)} callback.
15656         *
15657         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
15658         */
15659        public void onDrawShadow(Canvas canvas) {
15660            final View view = mView.get();
15661            if (view != null) {
15662                view.draw(canvas);
15663            } else {
15664                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
15665            }
15666        }
15667    }
15668
15669    /**
15670     * Starts a drag and drop operation. When your application calls this method, it passes a
15671     * {@link android.view.View.DragShadowBuilder} object to the system. The
15672     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
15673     * to get metrics for the drag shadow, and then calls the object's
15674     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
15675     * <p>
15676     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
15677     *  drag events to all the View objects in your application that are currently visible. It does
15678     *  this either by calling the View object's drag listener (an implementation of
15679     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
15680     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
15681     *  Both are passed a {@link android.view.DragEvent} object that has a
15682     *  {@link android.view.DragEvent#getAction()} value of
15683     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
15684     * </p>
15685     * <p>
15686     * Your application can invoke startDrag() on any attached View object. The View object does not
15687     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
15688     * be related to the View the user selected for dragging.
15689     * </p>
15690     * @param data A {@link android.content.ClipData} object pointing to the data to be
15691     * transferred by the drag and drop operation.
15692     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
15693     * drag shadow.
15694     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
15695     * drop operation. This Object is put into every DragEvent object sent by the system during the
15696     * current drag.
15697     * <p>
15698     * myLocalState is a lightweight mechanism for the sending information from the dragged View
15699     * to the target Views. For example, it can contain flags that differentiate between a
15700     * a copy operation and a move operation.
15701     * </p>
15702     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
15703     * so the parameter should be set to 0.
15704     * @return {@code true} if the method completes successfully, or
15705     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
15706     * do a drag, and so no drag operation is in progress.
15707     */
15708    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
15709            Object myLocalState, int flags) {
15710        if (ViewDebug.DEBUG_DRAG) {
15711            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
15712        }
15713        boolean okay = false;
15714
15715        Point shadowSize = new Point();
15716        Point shadowTouchPoint = new Point();
15717        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
15718
15719        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
15720                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
15721            throw new IllegalStateException("Drag shadow dimensions must not be negative");
15722        }
15723
15724        if (ViewDebug.DEBUG_DRAG) {
15725            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
15726                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
15727        }
15728        Surface surface = new Surface();
15729        try {
15730            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
15731                    flags, shadowSize.x, shadowSize.y, surface);
15732            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
15733                    + " surface=" + surface);
15734            if (token != null) {
15735                Canvas canvas = surface.lockCanvas(null);
15736                try {
15737                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
15738                    shadowBuilder.onDrawShadow(canvas);
15739                } finally {
15740                    surface.unlockCanvasAndPost(canvas);
15741                }
15742
15743                final ViewRootImpl root = getViewRootImpl();
15744
15745                // Cache the local state object for delivery with DragEvents
15746                root.setLocalDragState(myLocalState);
15747
15748                // repurpose 'shadowSize' for the last touch point
15749                root.getLastTouchPoint(shadowSize);
15750
15751                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
15752                        shadowSize.x, shadowSize.y,
15753                        shadowTouchPoint.x, shadowTouchPoint.y, data);
15754                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
15755
15756                // Off and running!  Release our local surface instance; the drag
15757                // shadow surface is now managed by the system process.
15758                surface.release();
15759            }
15760        } catch (Exception e) {
15761            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
15762            surface.destroy();
15763        }
15764
15765        return okay;
15766    }
15767
15768    /**
15769     * Handles drag events sent by the system following a call to
15770     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
15771     *<p>
15772     * When the system calls this method, it passes a
15773     * {@link android.view.DragEvent} object. A call to
15774     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
15775     * in DragEvent. The method uses these to determine what is happening in the drag and drop
15776     * operation.
15777     * @param event The {@link android.view.DragEvent} sent by the system.
15778     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
15779     * in DragEvent, indicating the type of drag event represented by this object.
15780     * @return {@code true} if the method was successful, otherwise {@code false}.
15781     * <p>
15782     *  The method should return {@code true} in response to an action type of
15783     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
15784     *  operation.
15785     * </p>
15786     * <p>
15787     *  The method should also return {@code true} in response to an action type of
15788     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
15789     *  {@code false} if it didn't.
15790     * </p>
15791     */
15792    public boolean onDragEvent(DragEvent event) {
15793        return false;
15794    }
15795
15796    /**
15797     * Detects if this View is enabled and has a drag event listener.
15798     * If both are true, then it calls the drag event listener with the
15799     * {@link android.view.DragEvent} it received. If the drag event listener returns
15800     * {@code true}, then dispatchDragEvent() returns {@code true}.
15801     * <p>
15802     * For all other cases, the method calls the
15803     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
15804     * method and returns its result.
15805     * </p>
15806     * <p>
15807     * This ensures that a drag event is always consumed, even if the View does not have a drag
15808     * event listener. However, if the View has a listener and the listener returns true, then
15809     * onDragEvent() is not called.
15810     * </p>
15811     */
15812    public boolean dispatchDragEvent(DragEvent event) {
15813        //noinspection SimplifiableIfStatement
15814        ListenerInfo li = mListenerInfo;
15815        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
15816                && li.mOnDragListener.onDrag(this, event)) {
15817            return true;
15818        }
15819        return onDragEvent(event);
15820    }
15821
15822    boolean canAcceptDrag() {
15823        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
15824    }
15825
15826    /**
15827     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
15828     * it is ever exposed at all.
15829     * @hide
15830     */
15831    public void onCloseSystemDialogs(String reason) {
15832    }
15833
15834    /**
15835     * Given a Drawable whose bounds have been set to draw into this view,
15836     * update a Region being computed for
15837     * {@link #gatherTransparentRegion(android.graphics.Region)} so
15838     * that any non-transparent parts of the Drawable are removed from the
15839     * given transparent region.
15840     *
15841     * @param dr The Drawable whose transparency is to be applied to the region.
15842     * @param region A Region holding the current transparency information,
15843     * where any parts of the region that are set are considered to be
15844     * transparent.  On return, this region will be modified to have the
15845     * transparency information reduced by the corresponding parts of the
15846     * Drawable that are not transparent.
15847     * {@hide}
15848     */
15849    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
15850        if (DBG) {
15851            Log.i("View", "Getting transparent region for: " + this);
15852        }
15853        final Region r = dr.getTransparentRegion();
15854        final Rect db = dr.getBounds();
15855        final AttachInfo attachInfo = mAttachInfo;
15856        if (r != null && attachInfo != null) {
15857            final int w = getRight()-getLeft();
15858            final int h = getBottom()-getTop();
15859            if (db.left > 0) {
15860                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
15861                r.op(0, 0, db.left, h, Region.Op.UNION);
15862            }
15863            if (db.right < w) {
15864                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
15865                r.op(db.right, 0, w, h, Region.Op.UNION);
15866            }
15867            if (db.top > 0) {
15868                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
15869                r.op(0, 0, w, db.top, Region.Op.UNION);
15870            }
15871            if (db.bottom < h) {
15872                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
15873                r.op(0, db.bottom, w, h, Region.Op.UNION);
15874            }
15875            final int[] location = attachInfo.mTransparentLocation;
15876            getLocationInWindow(location);
15877            r.translate(location[0], location[1]);
15878            region.op(r, Region.Op.INTERSECT);
15879        } else {
15880            region.op(db, Region.Op.DIFFERENCE);
15881        }
15882    }
15883
15884    private void checkForLongClick(int delayOffset) {
15885        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
15886            mHasPerformedLongPress = false;
15887
15888            if (mPendingCheckForLongPress == null) {
15889                mPendingCheckForLongPress = new CheckForLongPress();
15890            }
15891            mPendingCheckForLongPress.rememberWindowAttachCount();
15892            postDelayed(mPendingCheckForLongPress,
15893                    ViewConfiguration.getLongPressTimeout() - delayOffset);
15894        }
15895    }
15896
15897    /**
15898     * Inflate a view from an XML resource.  This convenience method wraps the {@link
15899     * LayoutInflater} class, which provides a full range of options for view inflation.
15900     *
15901     * @param context The Context object for your activity or application.
15902     * @param resource The resource ID to inflate
15903     * @param root A view group that will be the parent.  Used to properly inflate the
15904     * layout_* parameters.
15905     * @see LayoutInflater
15906     */
15907    public static View inflate(Context context, int resource, ViewGroup root) {
15908        LayoutInflater factory = LayoutInflater.from(context);
15909        return factory.inflate(resource, root);
15910    }
15911
15912    /**
15913     * Scroll the view with standard behavior for scrolling beyond the normal
15914     * content boundaries. Views that call this method should override
15915     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
15916     * results of an over-scroll operation.
15917     *
15918     * Views can use this method to handle any touch or fling-based scrolling.
15919     *
15920     * @param deltaX Change in X in pixels
15921     * @param deltaY Change in Y in pixels
15922     * @param scrollX Current X scroll value in pixels before applying deltaX
15923     * @param scrollY Current Y scroll value in pixels before applying deltaY
15924     * @param scrollRangeX Maximum content scroll range along the X axis
15925     * @param scrollRangeY Maximum content scroll range along the Y axis
15926     * @param maxOverScrollX Number of pixels to overscroll by in either direction
15927     *          along the X axis.
15928     * @param maxOverScrollY Number of pixels to overscroll by in either direction
15929     *          along the Y axis.
15930     * @param isTouchEvent true if this scroll operation is the result of a touch event.
15931     * @return true if scrolling was clamped to an over-scroll boundary along either
15932     *          axis, false otherwise.
15933     */
15934    @SuppressWarnings({"UnusedParameters"})
15935    protected boolean overScrollBy(int deltaX, int deltaY,
15936            int scrollX, int scrollY,
15937            int scrollRangeX, int scrollRangeY,
15938            int maxOverScrollX, int maxOverScrollY,
15939            boolean isTouchEvent) {
15940        final int overScrollMode = mOverScrollMode;
15941        final boolean canScrollHorizontal =
15942                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
15943        final boolean canScrollVertical =
15944                computeVerticalScrollRange() > computeVerticalScrollExtent();
15945        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
15946                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
15947        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
15948                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15949
15950        int newScrollX = scrollX + deltaX;
15951        if (!overScrollHorizontal) {
15952            maxOverScrollX = 0;
15953        }
15954
15955        int newScrollY = scrollY + deltaY;
15956        if (!overScrollVertical) {
15957            maxOverScrollY = 0;
15958        }
15959
15960        // Clamp values if at the limits and record
15961        final int left = -maxOverScrollX;
15962        final int right = maxOverScrollX + scrollRangeX;
15963        final int top = -maxOverScrollY;
15964        final int bottom = maxOverScrollY + scrollRangeY;
15965
15966        boolean clampedX = false;
15967        if (newScrollX > right) {
15968            newScrollX = right;
15969            clampedX = true;
15970        } else if (newScrollX < left) {
15971            newScrollX = left;
15972            clampedX = true;
15973        }
15974
15975        boolean clampedY = false;
15976        if (newScrollY > bottom) {
15977            newScrollY = bottom;
15978            clampedY = true;
15979        } else if (newScrollY < top) {
15980            newScrollY = top;
15981            clampedY = true;
15982        }
15983
15984        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
15985
15986        return clampedX || clampedY;
15987    }
15988
15989    /**
15990     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
15991     * respond to the results of an over-scroll operation.
15992     *
15993     * @param scrollX New X scroll value in pixels
15994     * @param scrollY New Y scroll value in pixels
15995     * @param clampedX True if scrollX was clamped to an over-scroll boundary
15996     * @param clampedY True if scrollY was clamped to an over-scroll boundary
15997     */
15998    protected void onOverScrolled(int scrollX, int scrollY,
15999            boolean clampedX, boolean clampedY) {
16000        // Intentionally empty.
16001    }
16002
16003    /**
16004     * Returns the over-scroll mode for this view. The result will be
16005     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16006     * (allow over-scrolling only if the view content is larger than the container),
16007     * or {@link #OVER_SCROLL_NEVER}.
16008     *
16009     * @return This view's over-scroll mode.
16010     */
16011    public int getOverScrollMode() {
16012        return mOverScrollMode;
16013    }
16014
16015    /**
16016     * Set the over-scroll mode for this view. Valid over-scroll modes are
16017     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16018     * (allow over-scrolling only if the view content is larger than the container),
16019     * or {@link #OVER_SCROLL_NEVER}.
16020     *
16021     * Setting the over-scroll mode of a view will have an effect only if the
16022     * view is capable of scrolling.
16023     *
16024     * @param overScrollMode The new over-scroll mode for this view.
16025     */
16026    public void setOverScrollMode(int overScrollMode) {
16027        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16028                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16029                overScrollMode != OVER_SCROLL_NEVER) {
16030            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16031        }
16032        mOverScrollMode = overScrollMode;
16033    }
16034
16035    /**
16036     * Gets a scale factor that determines the distance the view should scroll
16037     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16038     * @return The vertical scroll scale factor.
16039     * @hide
16040     */
16041    protected float getVerticalScrollFactor() {
16042        if (mVerticalScrollFactor == 0) {
16043            TypedValue outValue = new TypedValue();
16044            if (!mContext.getTheme().resolveAttribute(
16045                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16046                throw new IllegalStateException(
16047                        "Expected theme to define listPreferredItemHeight.");
16048            }
16049            mVerticalScrollFactor = outValue.getDimension(
16050                    mContext.getResources().getDisplayMetrics());
16051        }
16052        return mVerticalScrollFactor;
16053    }
16054
16055    /**
16056     * Gets a scale factor that determines the distance the view should scroll
16057     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16058     * @return The horizontal scroll scale factor.
16059     * @hide
16060     */
16061    protected float getHorizontalScrollFactor() {
16062        // TODO: Should use something else.
16063        return getVerticalScrollFactor();
16064    }
16065
16066    /**
16067     * Return the value specifying the text direction or policy that was set with
16068     * {@link #setTextDirection(int)}.
16069     *
16070     * @return the defined text direction. It can be one of:
16071     *
16072     * {@link #TEXT_DIRECTION_INHERIT},
16073     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16074     * {@link #TEXT_DIRECTION_ANY_RTL},
16075     * {@link #TEXT_DIRECTION_LTR},
16076     * {@link #TEXT_DIRECTION_RTL},
16077     * {@link #TEXT_DIRECTION_LOCALE}
16078     */
16079    @ViewDebug.ExportedProperty(category = "text", mapping = {
16080            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16081            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16082            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16083            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16084            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16085            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16086    })
16087    public int getTextDirection() {
16088        return (mPrivateFlags2 & TEXT_DIRECTION_MASK) >> TEXT_DIRECTION_MASK_SHIFT;
16089    }
16090
16091    /**
16092     * Set the text direction.
16093     *
16094     * @param textDirection the direction to set. Should be one of:
16095     *
16096     * {@link #TEXT_DIRECTION_INHERIT},
16097     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16098     * {@link #TEXT_DIRECTION_ANY_RTL},
16099     * {@link #TEXT_DIRECTION_LTR},
16100     * {@link #TEXT_DIRECTION_RTL},
16101     * {@link #TEXT_DIRECTION_LOCALE}
16102     */
16103    public void setTextDirection(int textDirection) {
16104        if (getTextDirection() != textDirection) {
16105            // Reset the current text direction and the resolved one
16106            mPrivateFlags2 &= ~TEXT_DIRECTION_MASK;
16107            resetResolvedTextDirection();
16108            // Set the new text direction
16109            mPrivateFlags2 |= ((textDirection << TEXT_DIRECTION_MASK_SHIFT) & TEXT_DIRECTION_MASK);
16110            // Refresh
16111            requestLayout();
16112            invalidate(true);
16113        }
16114    }
16115
16116    /**
16117     * Return the resolved text direction.
16118     *
16119     * This needs resolution if the value is TEXT_DIRECTION_INHERIT. The resolution matches
16120     * {@link #getTextDirection()}if it is not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds
16121     * up the parent chain of the view. if there is no parent, then it will return the default
16122     * {@link #TEXT_DIRECTION_FIRST_STRONG}.
16123     *
16124     * @return the resolved text direction. Returns one of:
16125     *
16126     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16127     * {@link #TEXT_DIRECTION_ANY_RTL},
16128     * {@link #TEXT_DIRECTION_LTR},
16129     * {@link #TEXT_DIRECTION_RTL},
16130     * {@link #TEXT_DIRECTION_LOCALE}
16131     */
16132    public int getResolvedTextDirection() {
16133        // The text direction will be resolved only if needed
16134        if ((mPrivateFlags2 & TEXT_DIRECTION_RESOLVED) != TEXT_DIRECTION_RESOLVED) {
16135            resolveTextDirection();
16136        }
16137        return (mPrivateFlags2 & TEXT_DIRECTION_RESOLVED_MASK) >> TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16138    }
16139
16140    /**
16141     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
16142     * resolution is done.
16143     */
16144    public void resolveTextDirection() {
16145        // Reset any previous text direction resolution
16146        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16147
16148        if (hasRtlSupport()) {
16149            // Set resolved text direction flag depending on text direction flag
16150            final int textDirection = getTextDirection();
16151            switch(textDirection) {
16152                case TEXT_DIRECTION_INHERIT:
16153                    if (canResolveTextDirection()) {
16154                        ViewGroup viewGroup = ((ViewGroup) mParent);
16155
16156                        // Set current resolved direction to the same value as the parent's one
16157                        final int parentResolvedDirection = viewGroup.getResolvedTextDirection();
16158                        switch (parentResolvedDirection) {
16159                            case TEXT_DIRECTION_FIRST_STRONG:
16160                            case TEXT_DIRECTION_ANY_RTL:
16161                            case TEXT_DIRECTION_LTR:
16162                            case TEXT_DIRECTION_RTL:
16163                            case TEXT_DIRECTION_LOCALE:
16164                                mPrivateFlags2 |=
16165                                        (parentResolvedDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16166                                break;
16167                            default:
16168                                // Default resolved direction is "first strong" heuristic
16169                                mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16170                        }
16171                    } else {
16172                        // We cannot do the resolution if there is no parent, so use the default one
16173                        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16174                    }
16175                    break;
16176                case TEXT_DIRECTION_FIRST_STRONG:
16177                case TEXT_DIRECTION_ANY_RTL:
16178                case TEXT_DIRECTION_LTR:
16179                case TEXT_DIRECTION_RTL:
16180                case TEXT_DIRECTION_LOCALE:
16181                    // Resolved direction is the same as text direction
16182                    mPrivateFlags2 |= (textDirection << TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16183                    break;
16184                default:
16185                    // Default resolved direction is "first strong" heuristic
16186                    mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16187            }
16188        } else {
16189            // Default resolved direction is "first strong" heuristic
16190            mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED_DEFAULT;
16191        }
16192
16193        // Set to resolved
16194        mPrivateFlags2 |= TEXT_DIRECTION_RESOLVED;
16195        onResolvedTextDirectionChanged();
16196    }
16197
16198    /**
16199     * Called when text direction has been resolved. Subclasses that care about text direction
16200     * resolution should override this method.
16201     *
16202     * The default implementation does nothing.
16203     */
16204    public void onResolvedTextDirectionChanged() {
16205    }
16206
16207    /**
16208     * Check if text direction resolution can be done.
16209     *
16210     * @return true if text direction resolution can be done otherwise return false.
16211     */
16212    public boolean canResolveTextDirection() {
16213        switch (getTextDirection()) {
16214            case TEXT_DIRECTION_INHERIT:
16215                return (mParent != null) && (mParent instanceof ViewGroup);
16216            default:
16217                return true;
16218        }
16219    }
16220
16221    /**
16222     * Reset resolved text direction. Text direction can be resolved with a call to
16223     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
16224     * reset is done.
16225     */
16226    public void resetResolvedTextDirection() {
16227        mPrivateFlags2 &= ~(TEXT_DIRECTION_RESOLVED | TEXT_DIRECTION_RESOLVED_MASK);
16228        onResolvedTextDirectionReset();
16229    }
16230
16231    /**
16232     * Called when text direction is reset. Subclasses that care about text direction reset should
16233     * override this method and do a reset of the text direction of their children. The default
16234     * implementation does nothing.
16235     */
16236    public void onResolvedTextDirectionReset() {
16237    }
16238
16239    /**
16240     * Return the value specifying the text alignment or policy that was set with
16241     * {@link #setTextAlignment(int)}.
16242     *
16243     * @return the defined text alignment. It can be one of:
16244     *
16245     * {@link #TEXT_ALIGNMENT_INHERIT},
16246     * {@link #TEXT_ALIGNMENT_GRAVITY},
16247     * {@link #TEXT_ALIGNMENT_CENTER},
16248     * {@link #TEXT_ALIGNMENT_TEXT_START},
16249     * {@link #TEXT_ALIGNMENT_TEXT_END},
16250     * {@link #TEXT_ALIGNMENT_VIEW_START},
16251     * {@link #TEXT_ALIGNMENT_VIEW_END}
16252     */
16253    @ViewDebug.ExportedProperty(category = "text", mapping = {
16254            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16255            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16256            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16257            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16258            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16259            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16260            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16261    })
16262    public int getTextAlignment() {
16263        return (mPrivateFlags2 & TEXT_ALIGNMENT_MASK) >> TEXT_ALIGNMENT_MASK_SHIFT;
16264    }
16265
16266    /**
16267     * Set the text alignment.
16268     *
16269     * @param textAlignment The text alignment to set. Should be one of
16270     *
16271     * {@link #TEXT_ALIGNMENT_INHERIT},
16272     * {@link #TEXT_ALIGNMENT_GRAVITY},
16273     * {@link #TEXT_ALIGNMENT_CENTER},
16274     * {@link #TEXT_ALIGNMENT_TEXT_START},
16275     * {@link #TEXT_ALIGNMENT_TEXT_END},
16276     * {@link #TEXT_ALIGNMENT_VIEW_START},
16277     * {@link #TEXT_ALIGNMENT_VIEW_END}
16278     *
16279     * @attr ref android.R.styleable#View_textAlignment
16280     */
16281    public void setTextAlignment(int textAlignment) {
16282        if (textAlignment != getTextAlignment()) {
16283            // Reset the current and resolved text alignment
16284            mPrivateFlags2 &= ~TEXT_ALIGNMENT_MASK;
16285            resetResolvedTextAlignment();
16286            // Set the new text alignment
16287            mPrivateFlags2 |= ((textAlignment << TEXT_ALIGNMENT_MASK_SHIFT) & TEXT_ALIGNMENT_MASK);
16288            // Refresh
16289            requestLayout();
16290            invalidate(true);
16291        }
16292    }
16293
16294    /**
16295     * Return the resolved text alignment.
16296     *
16297     * The resolved text alignment. This needs resolution if the value is
16298     * TEXT_ALIGNMENT_INHERIT. The resolution matches {@link #setTextAlignment(int)}  if it is
16299     * not TEXT_ALIGNMENT_INHERIT, otherwise resolution proceeds up the parent chain of the view.
16300     *
16301     * @return the resolved text alignment. Returns one of:
16302     *
16303     * {@link #TEXT_ALIGNMENT_GRAVITY},
16304     * {@link #TEXT_ALIGNMENT_CENTER},
16305     * {@link #TEXT_ALIGNMENT_TEXT_START},
16306     * {@link #TEXT_ALIGNMENT_TEXT_END},
16307     * {@link #TEXT_ALIGNMENT_VIEW_START},
16308     * {@link #TEXT_ALIGNMENT_VIEW_END}
16309     */
16310    @ViewDebug.ExportedProperty(category = "text", mapping = {
16311            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
16312            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
16313            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
16314            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
16315            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
16316            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
16317            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
16318    })
16319    public int getResolvedTextAlignment() {
16320        // If text alignment is not resolved, then resolve it
16321        if ((mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED) != TEXT_ALIGNMENT_RESOLVED) {
16322            resolveTextAlignment();
16323        }
16324        return (mPrivateFlags2 & TEXT_ALIGNMENT_RESOLVED_MASK) >> TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
16325    }
16326
16327    /**
16328     * Resolve the text alignment. Will call {@link View#onResolvedTextAlignmentChanged} when
16329     * resolution is done.
16330     */
16331    public void resolveTextAlignment() {
16332        // Reset any previous text alignment resolution
16333        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16334
16335        if (hasRtlSupport()) {
16336            // Set resolved text alignment flag depending on text alignment flag
16337            final int textAlignment = getTextAlignment();
16338            switch (textAlignment) {
16339                case TEXT_ALIGNMENT_INHERIT:
16340                    // Check if we can resolve the text alignment
16341                    if (canResolveLayoutDirection() && mParent instanceof View) {
16342                        View view = (View) mParent;
16343
16344                        final int parentResolvedTextAlignment = view.getResolvedTextAlignment();
16345                        switch (parentResolvedTextAlignment) {
16346                            case TEXT_ALIGNMENT_GRAVITY:
16347                            case TEXT_ALIGNMENT_TEXT_START:
16348                            case TEXT_ALIGNMENT_TEXT_END:
16349                            case TEXT_ALIGNMENT_CENTER:
16350                            case TEXT_ALIGNMENT_VIEW_START:
16351                            case TEXT_ALIGNMENT_VIEW_END:
16352                                // Resolved text alignment is the same as the parent resolved
16353                                // text alignment
16354                                mPrivateFlags2 |=
16355                                        (parentResolvedTextAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16356                                break;
16357                            default:
16358                                // Use default resolved text alignment
16359                                mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16360                        }
16361                    }
16362                    else {
16363                        // We cannot do the resolution if there is no parent so use the default
16364                        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16365                    }
16366                    break;
16367                case TEXT_ALIGNMENT_GRAVITY:
16368                case TEXT_ALIGNMENT_TEXT_START:
16369                case TEXT_ALIGNMENT_TEXT_END:
16370                case TEXT_ALIGNMENT_CENTER:
16371                case TEXT_ALIGNMENT_VIEW_START:
16372                case TEXT_ALIGNMENT_VIEW_END:
16373                    // Resolved text alignment is the same as text alignment
16374                    mPrivateFlags2 |= (textAlignment << TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
16375                    break;
16376                default:
16377                    // Use default resolved text alignment
16378                    mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16379            }
16380        } else {
16381            // Use default resolved text alignment
16382            mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED_DEFAULT;
16383        }
16384
16385        // Set the resolved
16386        mPrivateFlags2 |= TEXT_ALIGNMENT_RESOLVED;
16387        onResolvedTextAlignmentChanged();
16388    }
16389
16390    /**
16391     * Check if text alignment resolution can be done.
16392     *
16393     * @return true if text alignment resolution can be done otherwise return false.
16394     */
16395    public boolean canResolveTextAlignment() {
16396        switch (getTextAlignment()) {
16397            case TEXT_DIRECTION_INHERIT:
16398                return (mParent != null);
16399            default:
16400                return true;
16401        }
16402    }
16403
16404    /**
16405     * Called when text alignment has been resolved. Subclasses that care about text alignment
16406     * resolution should override this method.
16407     *
16408     * The default implementation does nothing.
16409     */
16410    public void onResolvedTextAlignmentChanged() {
16411    }
16412
16413    /**
16414     * Reset resolved text alignment. Text alignment can be resolved with a call to
16415     * getResolvedTextAlignment(). Will call {@link View#onResolvedTextAlignmentReset} when
16416     * reset is done.
16417     */
16418    public void resetResolvedTextAlignment() {
16419        // Reset any previous text alignment resolution
16420        mPrivateFlags2 &= ~(TEXT_ALIGNMENT_RESOLVED | TEXT_ALIGNMENT_RESOLVED_MASK);
16421        onResolvedTextAlignmentReset();
16422    }
16423
16424    /**
16425     * Called when text alignment is reset. Subclasses that care about text alignment reset should
16426     * override this method and do a reset of the text alignment of their children. The default
16427     * implementation does nothing.
16428     */
16429    public void onResolvedTextAlignmentReset() {
16430    }
16431
16432    /**
16433     * Generate a value suitable for use in {@link #setId(int)}.
16434     * This value will not collide with ID values generated at build time by aapt for R.id.
16435     *
16436     * @return a generated ID value
16437     */
16438    public static int generateViewId() {
16439        for (;;) {
16440            final int result = sNextGeneratedId.get();
16441            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
16442            int newValue = result + 1;
16443            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
16444            if (sNextGeneratedId.compareAndSet(result, newValue)) {
16445                return result;
16446            }
16447        }
16448    }
16449
16450    //
16451    // Properties
16452    //
16453    /**
16454     * A Property wrapper around the <code>alpha</code> functionality handled by the
16455     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
16456     */
16457    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
16458        @Override
16459        public void setValue(View object, float value) {
16460            object.setAlpha(value);
16461        }
16462
16463        @Override
16464        public Float get(View object) {
16465            return object.getAlpha();
16466        }
16467    };
16468
16469    /**
16470     * A Property wrapper around the <code>translationX</code> functionality handled by the
16471     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
16472     */
16473    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
16474        @Override
16475        public void setValue(View object, float value) {
16476            object.setTranslationX(value);
16477        }
16478
16479                @Override
16480        public Float get(View object) {
16481            return object.getTranslationX();
16482        }
16483    };
16484
16485    /**
16486     * A Property wrapper around the <code>translationY</code> functionality handled by the
16487     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
16488     */
16489    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
16490        @Override
16491        public void setValue(View object, float value) {
16492            object.setTranslationY(value);
16493        }
16494
16495        @Override
16496        public Float get(View object) {
16497            return object.getTranslationY();
16498        }
16499    };
16500
16501    /**
16502     * A Property wrapper around the <code>x</code> functionality handled by the
16503     * {@link View#setX(float)} and {@link View#getX()} methods.
16504     */
16505    public static final Property<View, Float> X = new FloatProperty<View>("x") {
16506        @Override
16507        public void setValue(View object, float value) {
16508            object.setX(value);
16509        }
16510
16511        @Override
16512        public Float get(View object) {
16513            return object.getX();
16514        }
16515    };
16516
16517    /**
16518     * A Property wrapper around the <code>y</code> functionality handled by the
16519     * {@link View#setY(float)} and {@link View#getY()} methods.
16520     */
16521    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
16522        @Override
16523        public void setValue(View object, float value) {
16524            object.setY(value);
16525        }
16526
16527        @Override
16528        public Float get(View object) {
16529            return object.getY();
16530        }
16531    };
16532
16533    /**
16534     * A Property wrapper around the <code>rotation</code> functionality handled by the
16535     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
16536     */
16537    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
16538        @Override
16539        public void setValue(View object, float value) {
16540            object.setRotation(value);
16541        }
16542
16543        @Override
16544        public Float get(View object) {
16545            return object.getRotation();
16546        }
16547    };
16548
16549    /**
16550     * A Property wrapper around the <code>rotationX</code> functionality handled by the
16551     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
16552     */
16553    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
16554        @Override
16555        public void setValue(View object, float value) {
16556            object.setRotationX(value);
16557        }
16558
16559        @Override
16560        public Float get(View object) {
16561            return object.getRotationX();
16562        }
16563    };
16564
16565    /**
16566     * A Property wrapper around the <code>rotationY</code> functionality handled by the
16567     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
16568     */
16569    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
16570        @Override
16571        public void setValue(View object, float value) {
16572            object.setRotationY(value);
16573        }
16574
16575        @Override
16576        public Float get(View object) {
16577            return object.getRotationY();
16578        }
16579    };
16580
16581    /**
16582     * A Property wrapper around the <code>scaleX</code> functionality handled by the
16583     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
16584     */
16585    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
16586        @Override
16587        public void setValue(View object, float value) {
16588            object.setScaleX(value);
16589        }
16590
16591        @Override
16592        public Float get(View object) {
16593            return object.getScaleX();
16594        }
16595    };
16596
16597    /**
16598     * A Property wrapper around the <code>scaleY</code> functionality handled by the
16599     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
16600     */
16601    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
16602        @Override
16603        public void setValue(View object, float value) {
16604            object.setScaleY(value);
16605        }
16606
16607        @Override
16608        public Float get(View object) {
16609            return object.getScaleY();
16610        }
16611    };
16612
16613    /**
16614     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
16615     * Each MeasureSpec represents a requirement for either the width or the height.
16616     * A MeasureSpec is comprised of a size and a mode. There are three possible
16617     * modes:
16618     * <dl>
16619     * <dt>UNSPECIFIED</dt>
16620     * <dd>
16621     * The parent has not imposed any constraint on the child. It can be whatever size
16622     * it wants.
16623     * </dd>
16624     *
16625     * <dt>EXACTLY</dt>
16626     * <dd>
16627     * The parent has determined an exact size for the child. The child is going to be
16628     * given those bounds regardless of how big it wants to be.
16629     * </dd>
16630     *
16631     * <dt>AT_MOST</dt>
16632     * <dd>
16633     * The child can be as large as it wants up to the specified size.
16634     * </dd>
16635     * </dl>
16636     *
16637     * MeasureSpecs are implemented as ints to reduce object allocation. This class
16638     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
16639     */
16640    public static class MeasureSpec {
16641        private static final int MODE_SHIFT = 30;
16642        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
16643
16644        /**
16645         * Measure specification mode: The parent has not imposed any constraint
16646         * on the child. It can be whatever size it wants.
16647         */
16648        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
16649
16650        /**
16651         * Measure specification mode: The parent has determined an exact size
16652         * for the child. The child is going to be given those bounds regardless
16653         * of how big it wants to be.
16654         */
16655        public static final int EXACTLY     = 1 << MODE_SHIFT;
16656
16657        /**
16658         * Measure specification mode: The child can be as large as it wants up
16659         * to the specified size.
16660         */
16661        public static final int AT_MOST     = 2 << MODE_SHIFT;
16662
16663        /**
16664         * Creates a measure specification based on the supplied size and mode.
16665         *
16666         * The mode must always be one of the following:
16667         * <ul>
16668         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
16669         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
16670         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
16671         * </ul>
16672         *
16673         * @param size the size of the measure specification
16674         * @param mode the mode of the measure specification
16675         * @return the measure specification based on size and mode
16676         */
16677        public static int makeMeasureSpec(int size, int mode) {
16678            return size + mode;
16679        }
16680
16681        /**
16682         * Extracts the mode from the supplied measure specification.
16683         *
16684         * @param measureSpec the measure specification to extract the mode from
16685         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
16686         *         {@link android.view.View.MeasureSpec#AT_MOST} or
16687         *         {@link android.view.View.MeasureSpec#EXACTLY}
16688         */
16689        public static int getMode(int measureSpec) {
16690            return (measureSpec & MODE_MASK);
16691        }
16692
16693        /**
16694         * Extracts the size from the supplied measure specification.
16695         *
16696         * @param measureSpec the measure specification to extract the size from
16697         * @return the size in pixels defined in the supplied measure specification
16698         */
16699        public static int getSize(int measureSpec) {
16700            return (measureSpec & ~MODE_MASK);
16701        }
16702
16703        /**
16704         * Returns a String representation of the specified measure
16705         * specification.
16706         *
16707         * @param measureSpec the measure specification to convert to a String
16708         * @return a String with the following format: "MeasureSpec: MODE SIZE"
16709         */
16710        public static String toString(int measureSpec) {
16711            int mode = getMode(measureSpec);
16712            int size = getSize(measureSpec);
16713
16714            StringBuilder sb = new StringBuilder("MeasureSpec: ");
16715
16716            if (mode == UNSPECIFIED)
16717                sb.append("UNSPECIFIED ");
16718            else if (mode == EXACTLY)
16719                sb.append("EXACTLY ");
16720            else if (mode == AT_MOST)
16721                sb.append("AT_MOST ");
16722            else
16723                sb.append(mode).append(" ");
16724
16725            sb.append(size);
16726            return sb.toString();
16727        }
16728    }
16729
16730    class CheckForLongPress implements Runnable {
16731
16732        private int mOriginalWindowAttachCount;
16733
16734        public void run() {
16735            if (isPressed() && (mParent != null)
16736                    && mOriginalWindowAttachCount == mWindowAttachCount) {
16737                if (performLongClick()) {
16738                    mHasPerformedLongPress = true;
16739                }
16740            }
16741        }
16742
16743        public void rememberWindowAttachCount() {
16744            mOriginalWindowAttachCount = mWindowAttachCount;
16745        }
16746    }
16747
16748    private final class CheckForTap implements Runnable {
16749        public void run() {
16750            mPrivateFlags &= ~PREPRESSED;
16751            setPressed(true);
16752            checkForLongClick(ViewConfiguration.getTapTimeout());
16753        }
16754    }
16755
16756    private final class PerformClick implements Runnable {
16757        public void run() {
16758            performClick();
16759        }
16760    }
16761
16762    /** @hide */
16763    public void hackTurnOffWindowResizeAnim(boolean off) {
16764        mAttachInfo.mTurnOffWindowResizeAnim = off;
16765    }
16766
16767    /**
16768     * This method returns a ViewPropertyAnimator object, which can be used to animate
16769     * specific properties on this View.
16770     *
16771     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
16772     */
16773    public ViewPropertyAnimator animate() {
16774        if (mAnimator == null) {
16775            mAnimator = new ViewPropertyAnimator(this);
16776        }
16777        return mAnimator;
16778    }
16779
16780    /**
16781     * Interface definition for a callback to be invoked when a hardware key event is
16782     * dispatched to this view. The callback will be invoked before the key event is
16783     * given to the view. This is only useful for hardware keyboards; a software input
16784     * method has no obligation to trigger this listener.
16785     */
16786    public interface OnKeyListener {
16787        /**
16788         * Called when a hardware key is dispatched to a view. This allows listeners to
16789         * get a chance to respond before the target view.
16790         * <p>Key presses in software keyboards will generally NOT trigger this method,
16791         * although some may elect to do so in some situations. Do not assume a
16792         * software input method has to be key-based; even if it is, it may use key presses
16793         * in a different way than you expect, so there is no way to reliably catch soft
16794         * input key presses.
16795         *
16796         * @param v The view the key has been dispatched to.
16797         * @param keyCode The code for the physical key that was pressed
16798         * @param event The KeyEvent object containing full information about
16799         *        the event.
16800         * @return True if the listener has consumed the event, false otherwise.
16801         */
16802        boolean onKey(View v, int keyCode, KeyEvent event);
16803    }
16804
16805    /**
16806     * Interface definition for a callback to be invoked when a touch event is
16807     * dispatched to this view. The callback will be invoked before the touch
16808     * event is given to the view.
16809     */
16810    public interface OnTouchListener {
16811        /**
16812         * Called when a touch event is dispatched to a view. This allows listeners to
16813         * get a chance to respond before the target view.
16814         *
16815         * @param v The view the touch event has been dispatched to.
16816         * @param event The MotionEvent object containing full information about
16817         *        the event.
16818         * @return True if the listener has consumed the event, false otherwise.
16819         */
16820        boolean onTouch(View v, MotionEvent event);
16821    }
16822
16823    /**
16824     * Interface definition for a callback to be invoked when a hover event is
16825     * dispatched to this view. The callback will be invoked before the hover
16826     * event is given to the view.
16827     */
16828    public interface OnHoverListener {
16829        /**
16830         * Called when a hover event is dispatched to a view. This allows listeners to
16831         * get a chance to respond before the target view.
16832         *
16833         * @param v The view the hover event has been dispatched to.
16834         * @param event The MotionEvent object containing full information about
16835         *        the event.
16836         * @return True if the listener has consumed the event, false otherwise.
16837         */
16838        boolean onHover(View v, MotionEvent event);
16839    }
16840
16841    /**
16842     * Interface definition for a callback to be invoked when a generic motion event is
16843     * dispatched to this view. The callback will be invoked before the generic motion
16844     * event is given to the view.
16845     */
16846    public interface OnGenericMotionListener {
16847        /**
16848         * Called when a generic motion event is dispatched to a view. This allows listeners to
16849         * get a chance to respond before the target view.
16850         *
16851         * @param v The view the generic motion event has been dispatched to.
16852         * @param event The MotionEvent object containing full information about
16853         *        the event.
16854         * @return True if the listener has consumed the event, false otherwise.
16855         */
16856        boolean onGenericMotion(View v, MotionEvent event);
16857    }
16858
16859    /**
16860     * Interface definition for a callback to be invoked when a view has been clicked and held.
16861     */
16862    public interface OnLongClickListener {
16863        /**
16864         * Called when a view has been clicked and held.
16865         *
16866         * @param v The view that was clicked and held.
16867         *
16868         * @return true if the callback consumed the long click, false otherwise.
16869         */
16870        boolean onLongClick(View v);
16871    }
16872
16873    /**
16874     * Interface definition for a callback to be invoked when a drag is being dispatched
16875     * to this view.  The callback will be invoked before the hosting view's own
16876     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
16877     * onDrag(event) behavior, it should return 'false' from this callback.
16878     *
16879     * <div class="special reference">
16880     * <h3>Developer Guides</h3>
16881     * <p>For a guide to implementing drag and drop features, read the
16882     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16883     * </div>
16884     */
16885    public interface OnDragListener {
16886        /**
16887         * Called when a drag event is dispatched to a view. This allows listeners
16888         * to get a chance to override base View behavior.
16889         *
16890         * @param v The View that received the drag event.
16891         * @param event The {@link android.view.DragEvent} object for the drag event.
16892         * @return {@code true} if the drag event was handled successfully, or {@code false}
16893         * if the drag event was not handled. Note that {@code false} will trigger the View
16894         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
16895         */
16896        boolean onDrag(View v, DragEvent event);
16897    }
16898
16899    /**
16900     * Interface definition for a callback to be invoked when the focus state of
16901     * a view changed.
16902     */
16903    public interface OnFocusChangeListener {
16904        /**
16905         * Called when the focus state of a view has changed.
16906         *
16907         * @param v The view whose state has changed.
16908         * @param hasFocus The new focus state of v.
16909         */
16910        void onFocusChange(View v, boolean hasFocus);
16911    }
16912
16913    /**
16914     * Interface definition for a callback to be invoked when a view is clicked.
16915     */
16916    public interface OnClickListener {
16917        /**
16918         * Called when a view has been clicked.
16919         *
16920         * @param v The view that was clicked.
16921         */
16922        void onClick(View v);
16923    }
16924
16925    /**
16926     * Interface definition for a callback to be invoked when the context menu
16927     * for this view is being built.
16928     */
16929    public interface OnCreateContextMenuListener {
16930        /**
16931         * Called when the context menu for this view is being built. It is not
16932         * safe to hold onto the menu after this method returns.
16933         *
16934         * @param menu The context menu that is being built
16935         * @param v The view for which the context menu is being built
16936         * @param menuInfo Extra information about the item for which the
16937         *            context menu should be shown. This information will vary
16938         *            depending on the class of v.
16939         */
16940        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
16941    }
16942
16943    /**
16944     * Interface definition for a callback to be invoked when the status bar changes
16945     * visibility.  This reports <strong>global</strong> changes to the system UI
16946     * state, not what the application is requesting.
16947     *
16948     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
16949     */
16950    public interface OnSystemUiVisibilityChangeListener {
16951        /**
16952         * Called when the status bar changes visibility because of a call to
16953         * {@link View#setSystemUiVisibility(int)}.
16954         *
16955         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16956         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
16957         * This tells you the <strong>global</strong> state of these UI visibility
16958         * flags, not what your app is currently applying.
16959         */
16960        public void onSystemUiVisibilityChange(int visibility);
16961    }
16962
16963    /**
16964     * Interface definition for a callback to be invoked when this view is attached
16965     * or detached from its window.
16966     */
16967    public interface OnAttachStateChangeListener {
16968        /**
16969         * Called when the view is attached to a window.
16970         * @param v The view that was attached
16971         */
16972        public void onViewAttachedToWindow(View v);
16973        /**
16974         * Called when the view is detached from a window.
16975         * @param v The view that was detached
16976         */
16977        public void onViewDetachedFromWindow(View v);
16978    }
16979
16980    private final class UnsetPressedState implements Runnable {
16981        public void run() {
16982            setPressed(false);
16983        }
16984    }
16985
16986    /**
16987     * Base class for derived classes that want to save and restore their own
16988     * state in {@link android.view.View#onSaveInstanceState()}.
16989     */
16990    public static class BaseSavedState extends AbsSavedState {
16991        /**
16992         * Constructor used when reading from a parcel. Reads the state of the superclass.
16993         *
16994         * @param source
16995         */
16996        public BaseSavedState(Parcel source) {
16997            super(source);
16998        }
16999
17000        /**
17001         * Constructor called by derived classes when creating their SavedState objects
17002         *
17003         * @param superState The state of the superclass of this view
17004         */
17005        public BaseSavedState(Parcelable superState) {
17006            super(superState);
17007        }
17008
17009        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17010                new Parcelable.Creator<BaseSavedState>() {
17011            public BaseSavedState createFromParcel(Parcel in) {
17012                return new BaseSavedState(in);
17013            }
17014
17015            public BaseSavedState[] newArray(int size) {
17016                return new BaseSavedState[size];
17017            }
17018        };
17019    }
17020
17021    /**
17022     * A set of information given to a view when it is attached to its parent
17023     * window.
17024     */
17025    static class AttachInfo {
17026        interface Callbacks {
17027            void playSoundEffect(int effectId);
17028            boolean performHapticFeedback(int effectId, boolean always);
17029        }
17030
17031        /**
17032         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17033         * to a Handler. This class contains the target (View) to invalidate and
17034         * the coordinates of the dirty rectangle.
17035         *
17036         * For performance purposes, this class also implements a pool of up to
17037         * POOL_LIMIT objects that get reused. This reduces memory allocations
17038         * whenever possible.
17039         */
17040        static class InvalidateInfo implements Poolable<InvalidateInfo> {
17041            private static final int POOL_LIMIT = 10;
17042            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
17043                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
17044                        public InvalidateInfo newInstance() {
17045                            return new InvalidateInfo();
17046                        }
17047
17048                        public void onAcquired(InvalidateInfo element) {
17049                        }
17050
17051                        public void onReleased(InvalidateInfo element) {
17052                            element.target = null;
17053                        }
17054                    }, POOL_LIMIT)
17055            );
17056
17057            private InvalidateInfo mNext;
17058            private boolean mIsPooled;
17059
17060            View target;
17061
17062            int left;
17063            int top;
17064            int right;
17065            int bottom;
17066
17067            public void setNextPoolable(InvalidateInfo element) {
17068                mNext = element;
17069            }
17070
17071            public InvalidateInfo getNextPoolable() {
17072                return mNext;
17073            }
17074
17075            static InvalidateInfo acquire() {
17076                return sPool.acquire();
17077            }
17078
17079            void release() {
17080                sPool.release(this);
17081            }
17082
17083            public boolean isPooled() {
17084                return mIsPooled;
17085            }
17086
17087            public void setPooled(boolean isPooled) {
17088                mIsPooled = isPooled;
17089            }
17090        }
17091
17092        final IWindowSession mSession;
17093
17094        final IWindow mWindow;
17095
17096        final IBinder mWindowToken;
17097
17098        final Callbacks mRootCallbacks;
17099
17100        HardwareCanvas mHardwareCanvas;
17101
17102        /**
17103         * The top view of the hierarchy.
17104         */
17105        View mRootView;
17106
17107        IBinder mPanelParentWindowToken;
17108        Surface mSurface;
17109
17110        boolean mHardwareAccelerated;
17111        boolean mHardwareAccelerationRequested;
17112        HardwareRenderer mHardwareRenderer;
17113
17114        boolean mScreenOn;
17115
17116        /**
17117         * Scale factor used by the compatibility mode
17118         */
17119        float mApplicationScale;
17120
17121        /**
17122         * Indicates whether the application is in compatibility mode
17123         */
17124        boolean mScalingRequired;
17125
17126        /**
17127         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
17128         */
17129        boolean mTurnOffWindowResizeAnim;
17130
17131        /**
17132         * Left position of this view's window
17133         */
17134        int mWindowLeft;
17135
17136        /**
17137         * Top position of this view's window
17138         */
17139        int mWindowTop;
17140
17141        /**
17142         * Indicates whether views need to use 32-bit drawing caches
17143         */
17144        boolean mUse32BitDrawingCache;
17145
17146        /**
17147         * For windows that are full-screen but using insets to layout inside
17148         * of the screen decorations, these are the current insets for the
17149         * content of the window.
17150         */
17151        final Rect mContentInsets = new Rect();
17152
17153        /**
17154         * For windows that are full-screen but using insets to layout inside
17155         * of the screen decorations, these are the current insets for the
17156         * actual visible parts of the window.
17157         */
17158        final Rect mVisibleInsets = new Rect();
17159
17160        /**
17161         * The internal insets given by this window.  This value is
17162         * supplied by the client (through
17163         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17164         * be given to the window manager when changed to be used in laying
17165         * out windows behind it.
17166         */
17167        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17168                = new ViewTreeObserver.InternalInsetsInfo();
17169
17170        /**
17171         * All views in the window's hierarchy that serve as scroll containers,
17172         * used to determine if the window can be resized or must be panned
17173         * to adjust for a soft input area.
17174         */
17175        final ArrayList<View> mScrollContainers = new ArrayList<View>();
17176
17177        final KeyEvent.DispatcherState mKeyDispatchState
17178                = new KeyEvent.DispatcherState();
17179
17180        /**
17181         * Indicates whether the view's window currently has the focus.
17182         */
17183        boolean mHasWindowFocus;
17184
17185        /**
17186         * The current visibility of the window.
17187         */
17188        int mWindowVisibility;
17189
17190        /**
17191         * Indicates the time at which drawing started to occur.
17192         */
17193        long mDrawingTime;
17194
17195        /**
17196         * Indicates whether or not ignoring the DIRTY_MASK flags.
17197         */
17198        boolean mIgnoreDirtyState;
17199
17200        /**
17201         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
17202         * to avoid clearing that flag prematurely.
17203         */
17204        boolean mSetIgnoreDirtyState = false;
17205
17206        /**
17207         * Indicates whether the view's window is currently in touch mode.
17208         */
17209        boolean mInTouchMode;
17210
17211        /**
17212         * Indicates that ViewAncestor should trigger a global layout change
17213         * the next time it performs a traversal
17214         */
17215        boolean mRecomputeGlobalAttributes;
17216
17217        /**
17218         * Always report new attributes at next traversal.
17219         */
17220        boolean mForceReportNewAttributes;
17221
17222        /**
17223         * Set during a traveral if any views want to keep the screen on.
17224         */
17225        boolean mKeepScreenOn;
17226
17227        /**
17228         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
17229         */
17230        int mSystemUiVisibility;
17231
17232        /**
17233         * Hack to force certain system UI visibility flags to be cleared.
17234         */
17235        int mDisabledSystemUiVisibility;
17236
17237        /**
17238         * Last global system UI visibility reported by the window manager.
17239         */
17240        int mGlobalSystemUiVisibility;
17241
17242        /**
17243         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
17244         * attached.
17245         */
17246        boolean mHasSystemUiListeners;
17247
17248        /**
17249         * Set if the visibility of any views has changed.
17250         */
17251        boolean mViewVisibilityChanged;
17252
17253        /**
17254         * Set to true if a view has been scrolled.
17255         */
17256        boolean mViewScrollChanged;
17257
17258        /**
17259         * Global to the view hierarchy used as a temporary for dealing with
17260         * x/y points in the transparent region computations.
17261         */
17262        final int[] mTransparentLocation = new int[2];
17263
17264        /**
17265         * Global to the view hierarchy used as a temporary for dealing with
17266         * x/y points in the ViewGroup.invalidateChild implementation.
17267         */
17268        final int[] mInvalidateChildLocation = new int[2];
17269
17270
17271        /**
17272         * Global to the view hierarchy used as a temporary for dealing with
17273         * x/y location when view is transformed.
17274         */
17275        final float[] mTmpTransformLocation = new float[2];
17276
17277        /**
17278         * The view tree observer used to dispatch global events like
17279         * layout, pre-draw, touch mode change, etc.
17280         */
17281        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
17282
17283        /**
17284         * A Canvas used by the view hierarchy to perform bitmap caching.
17285         */
17286        Canvas mCanvas;
17287
17288        /**
17289         * The view root impl.
17290         */
17291        final ViewRootImpl mViewRootImpl;
17292
17293        /**
17294         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
17295         * handler can be used to pump events in the UI events queue.
17296         */
17297        final Handler mHandler;
17298
17299        /**
17300         * Temporary for use in computing invalidate rectangles while
17301         * calling up the hierarchy.
17302         */
17303        final Rect mTmpInvalRect = new Rect();
17304
17305        /**
17306         * Temporary for use in computing hit areas with transformed views
17307         */
17308        final RectF mTmpTransformRect = new RectF();
17309
17310        /**
17311         * Temporary list for use in collecting focusable descendents of a view.
17312         */
17313        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
17314
17315        /**
17316         * The id of the window for accessibility purposes.
17317         */
17318        int mAccessibilityWindowId = View.NO_ID;
17319
17320        /**
17321         * Whether to ingore not exposed for accessibility Views when
17322         * reporting the view tree to accessibility services.
17323         */
17324        boolean mIncludeNotImportantViews;
17325
17326        /**
17327         * The drawable for highlighting accessibility focus.
17328         */
17329        Drawable mAccessibilityFocusDrawable;
17330
17331        /**
17332         * Show where the margins, bounds and layout bounds are for each view.
17333         */
17334        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
17335
17336        /**
17337         * Point used to compute visible regions.
17338         */
17339        final Point mPoint = new Point();
17340
17341        /**
17342         * Creates a new set of attachment information with the specified
17343         * events handler and thread.
17344         *
17345         * @param handler the events handler the view must use
17346         */
17347        AttachInfo(IWindowSession session, IWindow window,
17348                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
17349            mSession = session;
17350            mWindow = window;
17351            mWindowToken = window.asBinder();
17352            mViewRootImpl = viewRootImpl;
17353            mHandler = handler;
17354            mRootCallbacks = effectPlayer;
17355        }
17356    }
17357
17358    /**
17359     * <p>ScrollabilityCache holds various fields used by a View when scrolling
17360     * is supported. This avoids keeping too many unused fields in most
17361     * instances of View.</p>
17362     */
17363    private static class ScrollabilityCache implements Runnable {
17364
17365        /**
17366         * Scrollbars are not visible
17367         */
17368        public static final int OFF = 0;
17369
17370        /**
17371         * Scrollbars are visible
17372         */
17373        public static final int ON = 1;
17374
17375        /**
17376         * Scrollbars are fading away
17377         */
17378        public static final int FADING = 2;
17379
17380        public boolean fadeScrollBars;
17381
17382        public int fadingEdgeLength;
17383        public int scrollBarDefaultDelayBeforeFade;
17384        public int scrollBarFadeDuration;
17385
17386        public int scrollBarSize;
17387        public ScrollBarDrawable scrollBar;
17388        public float[] interpolatorValues;
17389        public View host;
17390
17391        public final Paint paint;
17392        public final Matrix matrix;
17393        public Shader shader;
17394
17395        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
17396
17397        private static final float[] OPAQUE = { 255 };
17398        private static final float[] TRANSPARENT = { 0.0f };
17399
17400        /**
17401         * When fading should start. This time moves into the future every time
17402         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
17403         */
17404        public long fadeStartTime;
17405
17406
17407        /**
17408         * The current state of the scrollbars: ON, OFF, or FADING
17409         */
17410        public int state = OFF;
17411
17412        private int mLastColor;
17413
17414        public ScrollabilityCache(ViewConfiguration configuration, View host) {
17415            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
17416            scrollBarSize = configuration.getScaledScrollBarSize();
17417            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
17418            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
17419
17420            paint = new Paint();
17421            matrix = new Matrix();
17422            // use use a height of 1, and then wack the matrix each time we
17423            // actually use it.
17424            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
17425
17426            paint.setShader(shader);
17427            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
17428            this.host = host;
17429        }
17430
17431        public void setFadeColor(int color) {
17432            if (color != 0 && color != mLastColor) {
17433                mLastColor = color;
17434                color |= 0xFF000000;
17435
17436                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
17437                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
17438
17439                paint.setShader(shader);
17440                // Restore the default transfer mode (src_over)
17441                paint.setXfermode(null);
17442            }
17443        }
17444
17445        public void run() {
17446            long now = AnimationUtils.currentAnimationTimeMillis();
17447            if (now >= fadeStartTime) {
17448
17449                // the animation fades the scrollbars out by changing
17450                // the opacity (alpha) from fully opaque to fully
17451                // transparent
17452                int nextFrame = (int) now;
17453                int framesCount = 0;
17454
17455                Interpolator interpolator = scrollBarInterpolator;
17456
17457                // Start opaque
17458                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
17459
17460                // End transparent
17461                nextFrame += scrollBarFadeDuration;
17462                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
17463
17464                state = FADING;
17465
17466                // Kick off the fade animation
17467                host.invalidate(true);
17468            }
17469        }
17470    }
17471
17472    /**
17473     * Resuable callback for sending
17474     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
17475     */
17476    private class SendViewScrolledAccessibilityEvent implements Runnable {
17477        public volatile boolean mIsPending;
17478
17479        public void run() {
17480            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
17481            mIsPending = false;
17482        }
17483    }
17484
17485    /**
17486     * <p>
17487     * This class represents a delegate that can be registered in a {@link View}
17488     * to enhance accessibility support via composition rather via inheritance.
17489     * It is specifically targeted to widget developers that extend basic View
17490     * classes i.e. classes in package android.view, that would like their
17491     * applications to be backwards compatible.
17492     * </p>
17493     * <div class="special reference">
17494     * <h3>Developer Guides</h3>
17495     * <p>For more information about making applications accessible, read the
17496     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
17497     * developer guide.</p>
17498     * </div>
17499     * <p>
17500     * A scenario in which a developer would like to use an accessibility delegate
17501     * is overriding a method introduced in a later API version then the minimal API
17502     * version supported by the application. For example, the method
17503     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
17504     * in API version 4 when the accessibility APIs were first introduced. If a
17505     * developer would like his application to run on API version 4 devices (assuming
17506     * all other APIs used by the application are version 4 or lower) and take advantage
17507     * of this method, instead of overriding the method which would break the application's
17508     * backwards compatibility, he can override the corresponding method in this
17509     * delegate and register the delegate in the target View if the API version of
17510     * the system is high enough i.e. the API version is same or higher to the API
17511     * version that introduced
17512     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
17513     * </p>
17514     * <p>
17515     * Here is an example implementation:
17516     * </p>
17517     * <code><pre><p>
17518     * if (Build.VERSION.SDK_INT >= 14) {
17519     *     // If the API version is equal of higher than the version in
17520     *     // which onInitializeAccessibilityNodeInfo was introduced we
17521     *     // register a delegate with a customized implementation.
17522     *     View view = findViewById(R.id.view_id);
17523     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
17524     *         public void onInitializeAccessibilityNodeInfo(View host,
17525     *                 AccessibilityNodeInfo info) {
17526     *             // Let the default implementation populate the info.
17527     *             super.onInitializeAccessibilityNodeInfo(host, info);
17528     *             // Set some other information.
17529     *             info.setEnabled(host.isEnabled());
17530     *         }
17531     *     });
17532     * }
17533     * </code></pre></p>
17534     * <p>
17535     * This delegate contains methods that correspond to the accessibility methods
17536     * in View. If a delegate has been specified the implementation in View hands
17537     * off handling to the corresponding method in this delegate. The default
17538     * implementation the delegate methods behaves exactly as the corresponding
17539     * method in View for the case of no accessibility delegate been set. Hence,
17540     * to customize the behavior of a View method, clients can override only the
17541     * corresponding delegate method without altering the behavior of the rest
17542     * accessibility related methods of the host view.
17543     * </p>
17544     */
17545    public static class AccessibilityDelegate {
17546
17547        /**
17548         * Sends an accessibility event of the given type. If accessibility is not
17549         * enabled this method has no effect.
17550         * <p>
17551         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
17552         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
17553         * been set.
17554         * </p>
17555         *
17556         * @param host The View hosting the delegate.
17557         * @param eventType The type of the event to send.
17558         *
17559         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
17560         */
17561        public void sendAccessibilityEvent(View host, int eventType) {
17562            host.sendAccessibilityEventInternal(eventType);
17563        }
17564
17565        /**
17566         * Performs the specified accessibility action on the view. For
17567         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
17568         * <p>
17569         * The default implementation behaves as
17570         * {@link View#performAccessibilityAction(int, Bundle)
17571         *  View#performAccessibilityAction(int, Bundle)} for the case of
17572         *  no accessibility delegate been set.
17573         * </p>
17574         *
17575         * @param action The action to perform.
17576         * @return Whether the action was performed.
17577         *
17578         * @see View#performAccessibilityAction(int, Bundle)
17579         *      View#performAccessibilityAction(int, Bundle)
17580         */
17581        public boolean performAccessibilityAction(View host, int action, Bundle args) {
17582            return host.performAccessibilityActionInternal(action, args);
17583        }
17584
17585        /**
17586         * Sends an accessibility event. This method behaves exactly as
17587         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
17588         * empty {@link AccessibilityEvent} and does not perform a check whether
17589         * accessibility is enabled.
17590         * <p>
17591         * The default implementation behaves as
17592         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17593         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
17594         * the case of no accessibility delegate been set.
17595         * </p>
17596         *
17597         * @param host The View hosting the delegate.
17598         * @param event The event to send.
17599         *
17600         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17601         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
17602         */
17603        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
17604            host.sendAccessibilityEventUncheckedInternal(event);
17605        }
17606
17607        /**
17608         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
17609         * to its children for adding their text content to the event.
17610         * <p>
17611         * The default implementation behaves as
17612         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17613         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
17614         * the case of no accessibility delegate been set.
17615         * </p>
17616         *
17617         * @param host The View hosting the delegate.
17618         * @param event The event.
17619         * @return True if the event population was completed.
17620         *
17621         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17622         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
17623         */
17624        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17625            return host.dispatchPopulateAccessibilityEventInternal(event);
17626        }
17627
17628        /**
17629         * Gives a chance to the host View to populate the accessibility event with its
17630         * text content.
17631         * <p>
17632         * The default implementation behaves as
17633         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
17634         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
17635         * the case of no accessibility delegate been set.
17636         * </p>
17637         *
17638         * @param host The View hosting the delegate.
17639         * @param event The accessibility event which to populate.
17640         *
17641         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
17642         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
17643         */
17644        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
17645            host.onPopulateAccessibilityEventInternal(event);
17646        }
17647
17648        /**
17649         * Initializes an {@link AccessibilityEvent} with information about the
17650         * the host View which is the event source.
17651         * <p>
17652         * The default implementation behaves as
17653         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
17654         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
17655         * the case of no accessibility delegate been set.
17656         * </p>
17657         *
17658         * @param host The View hosting the delegate.
17659         * @param event The event to initialize.
17660         *
17661         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
17662         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
17663         */
17664        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
17665            host.onInitializeAccessibilityEventInternal(event);
17666        }
17667
17668        /**
17669         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
17670         * <p>
17671         * The default implementation behaves as
17672         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17673         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
17674         * the case of no accessibility delegate been set.
17675         * </p>
17676         *
17677         * @param host The View hosting the delegate.
17678         * @param info The instance to initialize.
17679         *
17680         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17681         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
17682         */
17683        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
17684            host.onInitializeAccessibilityNodeInfoInternal(info);
17685        }
17686
17687        /**
17688         * Called when a child of the host View has requested sending an
17689         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
17690         * to augment the event.
17691         * <p>
17692         * The default implementation behaves as
17693         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17694         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
17695         * the case of no accessibility delegate been set.
17696         * </p>
17697         *
17698         * @param host The View hosting the delegate.
17699         * @param child The child which requests sending the event.
17700         * @param event The event to be sent.
17701         * @return True if the event should be sent
17702         *
17703         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17704         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
17705         */
17706        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
17707                AccessibilityEvent event) {
17708            return host.onRequestSendAccessibilityEventInternal(child, event);
17709        }
17710
17711        /**
17712         * Gets the provider for managing a virtual view hierarchy rooted at this View
17713         * and reported to {@link android.accessibilityservice.AccessibilityService}s
17714         * that explore the window content.
17715         * <p>
17716         * The default implementation behaves as
17717         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
17718         * the case of no accessibility delegate been set.
17719         * </p>
17720         *
17721         * @return The provider.
17722         *
17723         * @see AccessibilityNodeProvider
17724         */
17725        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
17726            return null;
17727        }
17728    }
17729}
17730