View.java revision b7045d2fb9d4b37333dbccb25a2ae9eee3b54577
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.hardware.display.DisplayManagerGlobal;
43import android.os.Build;
44import android.os.Bundle;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Parcel;
48import android.os.Parcelable;
49import android.os.RemoteException;
50import android.os.SystemClock;
51import android.os.SystemProperties;
52import android.text.TextUtils;
53import android.util.AttributeSet;
54import android.util.FloatProperty;
55import android.util.Log;
56import android.util.Pools.SynchronizedPool;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.AccessibilityIterators.TextSegmentIterator;
62import android.view.AccessibilityIterators.CharacterTextSegmentIterator;
63import android.view.AccessibilityIterators.WordTextSegmentIterator;
64import android.view.AccessibilityIterators.ParagraphTextSegmentIterator;
65import android.view.accessibility.AccessibilityEvent;
66import android.view.accessibility.AccessibilityEventSource;
67import android.view.accessibility.AccessibilityManager;
68import android.view.accessibility.AccessibilityNodeInfo;
69import android.view.accessibility.AccessibilityNodeProvider;
70import android.view.animation.Animation;
71import android.view.animation.AnimationUtils;
72import android.view.animation.Transformation;
73import android.view.inputmethod.EditorInfo;
74import android.view.inputmethod.InputConnection;
75import android.view.inputmethod.InputMethodManager;
76import android.widget.ScrollBarDrawable;
77
78import static android.os.Build.VERSION_CODES.*;
79import static java.lang.Math.max;
80
81import com.android.internal.R;
82import com.android.internal.util.Predicate;
83import com.android.internal.view.menu.MenuBuilder;
84import com.google.android.collect.Lists;
85import com.google.android.collect.Maps;
86
87import java.lang.ref.WeakReference;
88import java.lang.reflect.Field;
89import java.lang.reflect.InvocationTargetException;
90import java.lang.reflect.Method;
91import java.lang.reflect.Modifier;
92import java.util.ArrayList;
93import java.util.Arrays;
94import java.util.Collections;
95import java.util.HashMap;
96import java.util.Locale;
97import java.util.concurrent.CopyOnWriteArrayList;
98import java.util.concurrent.atomic.AtomicInteger;
99
100/**
101 * <p>
102 * This class represents the basic building block for user interface components. A View
103 * occupies a rectangular area on the screen and is responsible for drawing and
104 * event handling. View is the base class for <em>widgets</em>, which are
105 * used to create interactive UI components (buttons, text fields, etc.). The
106 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
107 * are invisible containers that hold other Views (or other ViewGroups) and define
108 * their layout properties.
109 * </p>
110 *
111 * <div class="special reference">
112 * <h3>Developer Guides</h3>
113 * <p>For information about using this class to develop your application's user interface,
114 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
115 * </div>
116 *
117 * <a name="Using"></a>
118 * <h3>Using Views</h3>
119 * <p>
120 * All of the views in a window are arranged in a single tree. You can add views
121 * either from code or by specifying a tree of views in one or more XML layout
122 * files. There are many specialized subclasses of views that act as controls or
123 * are capable of displaying text, images, or other content.
124 * </p>
125 * <p>
126 * Once you have created a tree of views, there are typically a few types of
127 * common operations you may wish to perform:
128 * <ul>
129 * <li><strong>Set properties:</strong> for example setting the text of a
130 * {@link android.widget.TextView}. The available properties and the methods
131 * that set them will vary among the different subclasses of views. Note that
132 * properties that are known at build time can be set in the XML layout
133 * files.</li>
134 * <li><strong>Set focus:</strong> The framework will handled moving focus in
135 * response to user input. To force focus to a specific view, call
136 * {@link #requestFocus}.</li>
137 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
138 * that will be notified when something interesting happens to the view. For
139 * example, all views will let you set a listener to be notified when the view
140 * gains or loses focus. You can register such a listener using
141 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
142 * Other view subclasses offer more specialized listeners. For example, a Button
143 * exposes a listener to notify clients when the button is clicked.</li>
144 * <li><strong>Set visibility:</strong> You can hide or show views using
145 * {@link #setVisibility(int)}.</li>
146 * </ul>
147 * </p>
148 * <p><em>
149 * Note: The Android framework is responsible for measuring, laying out and
150 * drawing views. You should not call methods that perform these actions on
151 * views yourself unless you are actually implementing a
152 * {@link android.view.ViewGroup}.
153 * </em></p>
154 *
155 * <a name="Lifecycle"></a>
156 * <h3>Implementing a Custom View</h3>
157 *
158 * <p>
159 * To implement a custom view, you will usually begin by providing overrides for
160 * some of the standard methods that the framework calls on all views. You do
161 * not need to override all of these methods. In fact, you can start by just
162 * overriding {@link #onDraw(android.graphics.Canvas)}.
163 * <table border="2" width="85%" align="center" cellpadding="5">
164 *     <thead>
165 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
166 *     </thead>
167 *
168 *     <tbody>
169 *     <tr>
170 *         <td rowspan="2">Creation</td>
171 *         <td>Constructors</td>
172 *         <td>There is a form of the constructor that are called when the view
173 *         is created from code and a form that is called when the view is
174 *         inflated from a layout file. The second form should parse and apply
175 *         any attributes defined in the layout file.
176 *         </td>
177 *     </tr>
178 *     <tr>
179 *         <td><code>{@link #onFinishInflate()}</code></td>
180 *         <td>Called after a view and all of its children has been inflated
181 *         from XML.</td>
182 *     </tr>
183 *
184 *     <tr>
185 *         <td rowspan="3">Layout</td>
186 *         <td><code>{@link #onMeasure(int, int)}</code></td>
187 *         <td>Called to determine the size requirements for this view and all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
193 *         <td>Called when this view should assign a size and position to all
194 *         of its children.
195 *         </td>
196 *     </tr>
197 *     <tr>
198 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
199 *         <td>Called when the size of this view has changed.
200 *         </td>
201 *     </tr>
202 *
203 *     <tr>
204 *         <td>Drawing</td>
205 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
206 *         <td>Called when the view should render its content.
207 *         </td>
208 *     </tr>
209 *
210 *     <tr>
211 *         <td rowspan="4">Event processing</td>
212 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
213 *         <td>Called when a new hardware key event occurs.
214 *         </td>
215 *     </tr>
216 *     <tr>
217 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
218 *         <td>Called when a hardware key up event occurs.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
223 *         <td>Called when a trackball motion event occurs.
224 *         </td>
225 *     </tr>
226 *     <tr>
227 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
228 *         <td>Called when a touch screen motion event occurs.
229 *         </td>
230 *     </tr>
231 *
232 *     <tr>
233 *         <td rowspan="2">Focus</td>
234 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
235 *         <td>Called when the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
241 *         <td>Called when the window containing the view gains or loses focus.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td rowspan="3">Attaching</td>
247 *         <td><code>{@link #onAttachedToWindow()}</code></td>
248 *         <td>Called when the view is attached to a window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onDetachedFromWindow}</code></td>
254 *         <td>Called when the view is detached from its window.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
260 *         <td>Called when the visibility of the window containing the view
261 *         has changed.
262 *         </td>
263 *     </tr>
264 *     </tbody>
265 *
266 * </table>
267 * </p>
268 *
269 * <a name="IDs"></a>
270 * <h3>IDs</h3>
271 * Views may have an integer id associated with them. These ids are typically
272 * assigned in the layout XML files, and are used to find specific views within
273 * the view tree. A common pattern is to:
274 * <ul>
275 * <li>Define a Button in the layout file and assign it a unique ID.
276 * <pre>
277 * &lt;Button
278 *     android:id="@+id/my_button"
279 *     android:layout_width="wrap_content"
280 *     android:layout_height="wrap_content"
281 *     android:text="@string/my_button_text"/&gt;
282 * </pre></li>
283 * <li>From the onCreate method of an Activity, find the Button
284 * <pre class="prettyprint">
285 *      Button myButton = (Button) findViewById(R.id.my_button);
286 * </pre></li>
287 * </ul>
288 * <p>
289 * View IDs need not be unique throughout the tree, but it is good practice to
290 * ensure that they are at least unique within the part of the tree you are
291 * searching.
292 * </p>
293 *
294 * <a name="Position"></a>
295 * <h3>Position</h3>
296 * <p>
297 * The geometry of a view is that of a rectangle. A view has a location,
298 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
299 * two dimensions, expressed as a width and a height. The unit for location
300 * and dimensions is the pixel.
301 * </p>
302 *
303 * <p>
304 * It is possible to retrieve the location of a view by invoking the methods
305 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
306 * coordinate of the rectangle representing the view. The latter returns the
307 * top, or Y, coordinate of the rectangle representing the view. These methods
308 * both return the location of the view relative to its parent. For instance,
309 * when getLeft() returns 20, that means the view is located 20 pixels to the
310 * right of the left edge of its direct parent.
311 * </p>
312 *
313 * <p>
314 * In addition, several convenience methods are offered to avoid unnecessary
315 * computations, namely {@link #getRight()} and {@link #getBottom()}.
316 * These methods return the coordinates of the right and bottom edges of the
317 * rectangle representing the view. For instance, calling {@link #getRight()}
318 * is similar to the following computation: <code>getLeft() + getWidth()</code>
319 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
320 * </p>
321 *
322 * <a name="SizePaddingMargins"></a>
323 * <h3>Size, padding and margins</h3>
324 * <p>
325 * The size of a view is expressed with a width and a height. A view actually
326 * possess two pairs of width and height values.
327 * </p>
328 *
329 * <p>
330 * The first pair is known as <em>measured width</em> and
331 * <em>measured height</em>. These dimensions define how big a view wants to be
332 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
333 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
334 * and {@link #getMeasuredHeight()}.
335 * </p>
336 *
337 * <p>
338 * The second pair is simply known as <em>width</em> and <em>height</em>, or
339 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
340 * dimensions define the actual size of the view on screen, at drawing time and
341 * after layout. These values may, but do not have to, be different from the
342 * measured width and height. The width and height can be obtained by calling
343 * {@link #getWidth()} and {@link #getHeight()}.
344 * </p>
345 *
346 * <p>
347 * To measure its dimensions, a view takes into account its padding. The padding
348 * is expressed in pixels for the left, top, right and bottom parts of the view.
349 * Padding can be used to offset the content of the view by a specific amount of
350 * pixels. For instance, a left padding of 2 will push the view's content by
351 * 2 pixels to the right of the left edge. Padding can be set using the
352 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
353 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
354 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
355 * {@link #getPaddingEnd()}.
356 * </p>
357 *
358 * <p>
359 * Even though a view can define a padding, it does not provide any support for
360 * margins. However, view groups provide such a support. Refer to
361 * {@link android.view.ViewGroup} and
362 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
363 * </p>
364 *
365 * <a name="Layout"></a>
366 * <h3>Layout</h3>
367 * <p>
368 * Layout is a two pass process: a measure pass and a layout pass. The measuring
369 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
370 * of the view tree. Each view pushes dimension specifications down the tree
371 * during the recursion. At the end of the measure pass, every view has stored
372 * its measurements. The second pass happens in
373 * {@link #layout(int,int,int,int)} and is also top-down. During
374 * this pass each parent is responsible for positioning all of its children
375 * using the sizes computed in the measure pass.
376 * </p>
377 *
378 * <p>
379 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
380 * {@link #getMeasuredHeight()} values must be set, along with those for all of
381 * that view's descendants. A view's measured width and measured height values
382 * must respect the constraints imposed by the view's parents. This guarantees
383 * that at the end of the measure pass, all parents accept all of their
384 * children's measurements. A parent view may call measure() more than once on
385 * its children. For example, the parent may measure each child once with
386 * unspecified dimensions to find out how big they want to be, then call
387 * measure() on them again with actual numbers if the sum of all the children's
388 * unconstrained sizes is too big or too small.
389 * </p>
390 *
391 * <p>
392 * The measure pass uses two classes to communicate dimensions. The
393 * {@link MeasureSpec} class is used by views to tell their parents how they
394 * want to be measured and positioned. The base LayoutParams class just
395 * describes how big the view wants to be for both width and height. For each
396 * dimension, it can specify one of:
397 * <ul>
398 * <li> an exact number
399 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
400 * (minus padding)
401 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
402 * enclose its content (plus padding).
403 * </ul>
404 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
405 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
406 * an X and Y value.
407 * </p>
408 *
409 * <p>
410 * MeasureSpecs are used to push requirements down the tree from parent to
411 * child. A MeasureSpec can be in one of three modes:
412 * <ul>
413 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
414 * of a child view. For example, a LinearLayout may call measure() on its child
415 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
416 * tall the child view wants to be given a width of 240 pixels.
417 * <li>EXACTLY: This is used by the parent to impose an exact size on the
418 * child. The child must use this size, and guarantee that all of its
419 * descendants will fit within this size.
420 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
421 * child. The child must gurantee that it and all of its descendants will fit
422 * within this size.
423 * </ul>
424 * </p>
425 *
426 * <p>
427 * To intiate a layout, call {@link #requestLayout}. This method is typically
428 * called by a view on itself when it believes that is can no longer fit within
429 * its current bounds.
430 * </p>
431 *
432 * <a name="Drawing"></a>
433 * <h3>Drawing</h3>
434 * <p>
435 * Drawing is handled by walking the tree and rendering each view that
436 * intersects the invalid region. Because the tree is traversed in-order,
437 * this means that parents will draw before (i.e., behind) their children, with
438 * siblings drawn in the order they appear in the tree.
439 * If you set a background drawable for a View, then the View will draw it for you
440 * before calling back to its <code>onDraw()</code> method.
441 * </p>
442 *
443 * <p>
444 * Note that the framework will not draw views that are not in the invalid region.
445 * </p>
446 *
447 * <p>
448 * To force a view to draw, call {@link #invalidate()}.
449 * </p>
450 *
451 * <a name="EventHandlingThreading"></a>
452 * <h3>Event Handling and Threading</h3>
453 * <p>
454 * The basic cycle of a view is as follows:
455 * <ol>
456 * <li>An event comes in and is dispatched to the appropriate view. The view
457 * handles the event and notifies any listeners.</li>
458 * <li>If in the course of processing the event, the view's bounds may need
459 * to be changed, the view will call {@link #requestLayout()}.</li>
460 * <li>Similarly, if in the course of processing the event the view's appearance
461 * may need to be changed, the view will call {@link #invalidate()}.</li>
462 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
463 * the framework will take care of measuring, laying out, and drawing the tree
464 * as appropriate.</li>
465 * </ol>
466 * </p>
467 *
468 * <p><em>Note: The entire view tree is single threaded. You must always be on
469 * the UI thread when calling any method on any view.</em>
470 * If you are doing work on other threads and want to update the state of a view
471 * from that thread, you should use a {@link Handler}.
472 * </p>
473 *
474 * <a name="FocusHandling"></a>
475 * <h3>Focus Handling</h3>
476 * <p>
477 * The framework will handle routine focus movement in response to user input.
478 * This includes changing the focus as views are removed or hidden, or as new
479 * views become available. Views indicate their willingness to take focus
480 * through the {@link #isFocusable} method. To change whether a view can take
481 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
482 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
483 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
484 * </p>
485 * <p>
486 * Focus movement is based on an algorithm which finds the nearest neighbor in a
487 * given direction. In rare cases, the default algorithm may not match the
488 * intended behavior of the developer. In these situations, you can provide
489 * explicit overrides by using these XML attributes in the layout file:
490 * <pre>
491 * nextFocusDown
492 * nextFocusLeft
493 * nextFocusRight
494 * nextFocusUp
495 * </pre>
496 * </p>
497 *
498 *
499 * <p>
500 * To get a particular view to take focus, call {@link #requestFocus()}.
501 * </p>
502 *
503 * <a name="TouchMode"></a>
504 * <h3>Touch Mode</h3>
505 * <p>
506 * When a user is navigating a user interface via directional keys such as a D-pad, it is
507 * necessary to give focus to actionable items such as buttons so the user can see
508 * what will take input.  If the device has touch capabilities, however, and the user
509 * begins interacting with the interface by touching it, it is no longer necessary to
510 * always highlight, or give focus to, a particular view.  This motivates a mode
511 * for interaction named 'touch mode'.
512 * </p>
513 * <p>
514 * For a touch capable device, once the user touches the screen, the device
515 * will enter touch mode.  From this point onward, only views for which
516 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
517 * Other views that are touchable, like buttons, will not take focus when touched; they will
518 * only fire the on click listeners.
519 * </p>
520 * <p>
521 * Any time a user hits a directional key, such as a D-pad direction, the view device will
522 * exit touch mode, and find a view to take focus, so that the user may resume interacting
523 * with the user interface without touching the screen again.
524 * </p>
525 * <p>
526 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
527 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
528 * </p>
529 *
530 * <a name="Scrolling"></a>
531 * <h3>Scrolling</h3>
532 * <p>
533 * The framework provides basic support for views that wish to internally
534 * scroll their content. This includes keeping track of the X and Y scroll
535 * offset as well as mechanisms for drawing scrollbars. See
536 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
537 * {@link #awakenScrollBars()} for more details.
538 * </p>
539 *
540 * <a name="Tags"></a>
541 * <h3>Tags</h3>
542 * <p>
543 * Unlike IDs, tags are not used to identify views. Tags are essentially an
544 * extra piece of information that can be associated with a view. They are most
545 * often used as a convenience to store data related to views in the views
546 * themselves rather than by putting them in a separate structure.
547 * </p>
548 *
549 * <a name="Properties"></a>
550 * <h3>Properties</h3>
551 * <p>
552 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
553 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
554 * available both in the {@link Property} form as well as in similarly-named setter/getter
555 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
556 * be used to set persistent state associated with these rendering-related properties on the view.
557 * The properties and methods can also be used in conjunction with
558 * {@link android.animation.Animator Animator}-based animations, described more in the
559 * <a href="#Animation">Animation</a> section.
560 * </p>
561 *
562 * <a name="Animation"></a>
563 * <h3>Animation</h3>
564 * <p>
565 * Starting with Android 3.0, the preferred way of animating views is to use the
566 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
567 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
568 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
569 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
570 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
571 * makes animating these View properties particularly easy and efficient.
572 * </p>
573 * <p>
574 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
575 * You can attach an {@link Animation} object to a view using
576 * {@link #setAnimation(Animation)} or
577 * {@link #startAnimation(Animation)}. The animation can alter the scale,
578 * rotation, translation and alpha of a view over time. If the animation is
579 * attached to a view that has children, the animation will affect the entire
580 * subtree rooted by that node. When an animation is started, the framework will
581 * take care of redrawing the appropriate views until the animation completes.
582 * </p>
583 *
584 * <a name="Security"></a>
585 * <h3>Security</h3>
586 * <p>
587 * Sometimes it is essential that an application be able to verify that an action
588 * is being performed with the full knowledge and consent of the user, such as
589 * granting a permission request, making a purchase or clicking on an advertisement.
590 * Unfortunately, a malicious application could try to spoof the user into
591 * performing these actions, unaware, by concealing the intended purpose of the view.
592 * As a remedy, the framework offers a touch filtering mechanism that can be used to
593 * improve the security of views that provide access to sensitive functionality.
594 * </p><p>
595 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
596 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
597 * will discard touches that are received whenever the view's window is obscured by
598 * another visible window.  As a result, the view will not receive touches whenever a
599 * toast, dialog or other window appears above the view's window.
600 * </p><p>
601 * For more fine-grained control over security, consider overriding the
602 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
603 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
604 * </p>
605 *
606 * @attr ref android.R.styleable#View_alpha
607 * @attr ref android.R.styleable#View_background
608 * @attr ref android.R.styleable#View_clickable
609 * @attr ref android.R.styleable#View_contentDescription
610 * @attr ref android.R.styleable#View_drawingCacheQuality
611 * @attr ref android.R.styleable#View_duplicateParentState
612 * @attr ref android.R.styleable#View_id
613 * @attr ref android.R.styleable#View_requiresFadingEdge
614 * @attr ref android.R.styleable#View_fadeScrollbars
615 * @attr ref android.R.styleable#View_fadingEdgeLength
616 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
617 * @attr ref android.R.styleable#View_fitsSystemWindows
618 * @attr ref android.R.styleable#View_isScrollContainer
619 * @attr ref android.R.styleable#View_focusable
620 * @attr ref android.R.styleable#View_focusableInTouchMode
621 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
622 * @attr ref android.R.styleable#View_keepScreenOn
623 * @attr ref android.R.styleable#View_layerType
624 * @attr ref android.R.styleable#View_layoutDirection
625 * @attr ref android.R.styleable#View_longClickable
626 * @attr ref android.R.styleable#View_minHeight
627 * @attr ref android.R.styleable#View_minWidth
628 * @attr ref android.R.styleable#View_nextFocusDown
629 * @attr ref android.R.styleable#View_nextFocusLeft
630 * @attr ref android.R.styleable#View_nextFocusRight
631 * @attr ref android.R.styleable#View_nextFocusUp
632 * @attr ref android.R.styleable#View_onClick
633 * @attr ref android.R.styleable#View_padding
634 * @attr ref android.R.styleable#View_paddingBottom
635 * @attr ref android.R.styleable#View_paddingLeft
636 * @attr ref android.R.styleable#View_paddingRight
637 * @attr ref android.R.styleable#View_paddingTop
638 * @attr ref android.R.styleable#View_paddingStart
639 * @attr ref android.R.styleable#View_paddingEnd
640 * @attr ref android.R.styleable#View_saveEnabled
641 * @attr ref android.R.styleable#View_rotation
642 * @attr ref android.R.styleable#View_rotationX
643 * @attr ref android.R.styleable#View_rotationY
644 * @attr ref android.R.styleable#View_scaleX
645 * @attr ref android.R.styleable#View_scaleY
646 * @attr ref android.R.styleable#View_scrollX
647 * @attr ref android.R.styleable#View_scrollY
648 * @attr ref android.R.styleable#View_scrollbarSize
649 * @attr ref android.R.styleable#View_scrollbarStyle
650 * @attr ref android.R.styleable#View_scrollbars
651 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
652 * @attr ref android.R.styleable#View_scrollbarFadeDuration
653 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
654 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
655 * @attr ref android.R.styleable#View_scrollbarThumbVertical
656 * @attr ref android.R.styleable#View_scrollbarTrackVertical
657 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
659 * @attr ref android.R.styleable#View_soundEffectsEnabled
660 * @attr ref android.R.styleable#View_tag
661 * @attr ref android.R.styleable#View_textAlignment
662 * @attr ref android.R.styleable#View_textDirection
663 * @attr ref android.R.styleable#View_transformPivotX
664 * @attr ref android.R.styleable#View_transformPivotY
665 * @attr ref android.R.styleable#View_translationX
666 * @attr ref android.R.styleable#View_translationY
667 * @attr ref android.R.styleable#View_visibility
668 *
669 * @see android.view.ViewGroup
670 */
671public class View implements Drawable.Callback, KeyEvent.Callback,
672        AccessibilityEventSource {
673    private static final boolean DBG = false;
674
675    /**
676     * The logging tag used by this class with android.util.Log.
677     */
678    protected static final String VIEW_LOG_TAG = "View";
679
680    /**
681     * When set to true, apps will draw debugging information about their layouts.
682     *
683     * @hide
684     */
685    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
686
687    /**
688     * Used to mark a View that has no ID.
689     */
690    public static final int NO_ID = -1;
691
692    private static boolean sUseBrokenMakeMeasureSpec = false;
693
694    /**
695     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
696     * calling setFlags.
697     */
698    private static final int NOT_FOCUSABLE = 0x00000000;
699
700    /**
701     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
702     * setFlags.
703     */
704    private static final int FOCUSABLE = 0x00000001;
705
706    /**
707     * Mask for use with setFlags indicating bits used for focus.
708     */
709    private static final int FOCUSABLE_MASK = 0x00000001;
710
711    /**
712     * This view will adjust its padding to fit sytem windows (e.g. status bar)
713     */
714    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
715
716    /**
717     * This view is visible.
718     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
719     * android:visibility}.
720     */
721    public static final int VISIBLE = 0x00000000;
722
723    /**
724     * This view is invisible, but it still takes up space for layout purposes.
725     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
726     * android:visibility}.
727     */
728    public static final int INVISIBLE = 0x00000004;
729
730    /**
731     * This view is invisible, and it doesn't take any space for layout
732     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
733     * android:visibility}.
734     */
735    public static final int GONE = 0x00000008;
736
737    /**
738     * Mask for use with setFlags indicating bits used for visibility.
739     * {@hide}
740     */
741    static final int VISIBILITY_MASK = 0x0000000C;
742
743    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
744
745    /**
746     * This view is enabled. Interpretation varies by subclass.
747     * Use with ENABLED_MASK when calling setFlags.
748     * {@hide}
749     */
750    static final int ENABLED = 0x00000000;
751
752    /**
753     * This view is disabled. Interpretation varies by subclass.
754     * Use with ENABLED_MASK when calling setFlags.
755     * {@hide}
756     */
757    static final int DISABLED = 0x00000020;
758
759   /**
760    * Mask for use with setFlags indicating bits used for indicating whether
761    * this view is enabled
762    * {@hide}
763    */
764    static final int ENABLED_MASK = 0x00000020;
765
766    /**
767     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
768     * called and further optimizations will be performed. It is okay to have
769     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
770     * {@hide}
771     */
772    static final int WILL_NOT_DRAW = 0x00000080;
773
774    /**
775     * Mask for use with setFlags indicating bits used for indicating whether
776     * this view is will draw
777     * {@hide}
778     */
779    static final int DRAW_MASK = 0x00000080;
780
781    /**
782     * <p>This view doesn't show scrollbars.</p>
783     * {@hide}
784     */
785    static final int SCROLLBARS_NONE = 0x00000000;
786
787    /**
788     * <p>This view shows horizontal scrollbars.</p>
789     * {@hide}
790     */
791    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
792
793    /**
794     * <p>This view shows vertical scrollbars.</p>
795     * {@hide}
796     */
797    static final int SCROLLBARS_VERTICAL = 0x00000200;
798
799    /**
800     * <p>Mask for use with setFlags indicating bits used for indicating which
801     * scrollbars are enabled.</p>
802     * {@hide}
803     */
804    static final int SCROLLBARS_MASK = 0x00000300;
805
806    /**
807     * Indicates that the view should filter touches when its window is obscured.
808     * Refer to the class comments for more information about this security feature.
809     * {@hide}
810     */
811    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
812
813    /**
814     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
815     * that they are optional and should be skipped if the window has
816     * requested system UI flags that ignore those insets for layout.
817     */
818    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
819
820    /**
821     * <p>This view doesn't show fading edges.</p>
822     * {@hide}
823     */
824    static final int FADING_EDGE_NONE = 0x00000000;
825
826    /**
827     * <p>This view shows horizontal fading edges.</p>
828     * {@hide}
829     */
830    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
831
832    /**
833     * <p>This view shows vertical fading edges.</p>
834     * {@hide}
835     */
836    static final int FADING_EDGE_VERTICAL = 0x00002000;
837
838    /**
839     * <p>Mask for use with setFlags indicating bits used for indicating which
840     * fading edges are enabled.</p>
841     * {@hide}
842     */
843    static final int FADING_EDGE_MASK = 0x00003000;
844
845    /**
846     * <p>Indicates this view can be clicked. When clickable, a View reacts
847     * to clicks by notifying the OnClickListener.<p>
848     * {@hide}
849     */
850    static final int CLICKABLE = 0x00004000;
851
852    /**
853     * <p>Indicates this view is caching its drawing into a bitmap.</p>
854     * {@hide}
855     */
856    static final int DRAWING_CACHE_ENABLED = 0x00008000;
857
858    /**
859     * <p>Indicates that no icicle should be saved for this view.<p>
860     * {@hide}
861     */
862    static final int SAVE_DISABLED = 0x000010000;
863
864    /**
865     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
866     * property.</p>
867     * {@hide}
868     */
869    static final int SAVE_DISABLED_MASK = 0x000010000;
870
871    /**
872     * <p>Indicates that no drawing cache should ever be created for this view.<p>
873     * {@hide}
874     */
875    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
876
877    /**
878     * <p>Indicates this view can take / keep focus when int touch mode.</p>
879     * {@hide}
880     */
881    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
882
883    /**
884     * <p>Enables low quality mode for the drawing cache.</p>
885     */
886    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
887
888    /**
889     * <p>Enables high quality mode for the drawing cache.</p>
890     */
891    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
892
893    /**
894     * <p>Enables automatic quality mode for the drawing cache.</p>
895     */
896    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
897
898    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
899            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
900    };
901
902    /**
903     * <p>Mask for use with setFlags indicating bits used for the cache
904     * quality property.</p>
905     * {@hide}
906     */
907    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
908
909    /**
910     * <p>
911     * Indicates this view can be long clicked. When long clickable, a View
912     * reacts to long clicks by notifying the OnLongClickListener or showing a
913     * context menu.
914     * </p>
915     * {@hide}
916     */
917    static final int LONG_CLICKABLE = 0x00200000;
918
919    /**
920     * <p>Indicates that this view gets its drawable states from its direct parent
921     * and ignores its original internal states.</p>
922     *
923     * @hide
924     */
925    static final int DUPLICATE_PARENT_STATE = 0x00400000;
926
927    /**
928     * The scrollbar style to display the scrollbars inside the content area,
929     * without increasing the padding. The scrollbars will be overlaid with
930     * translucency on the view's content.
931     */
932    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
933
934    /**
935     * The scrollbar style to display the scrollbars inside the padded area,
936     * increasing the padding of the view. The scrollbars will not overlap the
937     * content area of the view.
938     */
939    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
940
941    /**
942     * The scrollbar style to display the scrollbars at the edge of the view,
943     * without increasing the padding. The scrollbars will be overlaid with
944     * translucency.
945     */
946    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
947
948    /**
949     * The scrollbar style to display the scrollbars at the edge of the view,
950     * increasing the padding of the view. The scrollbars will only overlap the
951     * background, if any.
952     */
953    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
954
955    /**
956     * Mask to check if the scrollbar style is overlay or inset.
957     * {@hide}
958     */
959    static final int SCROLLBARS_INSET_MASK = 0x01000000;
960
961    /**
962     * Mask to check if the scrollbar style is inside or outside.
963     * {@hide}
964     */
965    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
966
967    /**
968     * Mask for scrollbar style.
969     * {@hide}
970     */
971    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
972
973    /**
974     * View flag indicating that the screen should remain on while the
975     * window containing this view is visible to the user.  This effectively
976     * takes care of automatically setting the WindowManager's
977     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
978     */
979    public static final int KEEP_SCREEN_ON = 0x04000000;
980
981    /**
982     * View flag indicating whether this view should have sound effects enabled
983     * for events such as clicking and touching.
984     */
985    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
986
987    /**
988     * View flag indicating whether this view should have haptic feedback
989     * enabled for events such as long presses.
990     */
991    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
992
993    /**
994     * <p>Indicates that the view hierarchy should stop saving state when
995     * it reaches this view.  If state saving is initiated immediately at
996     * the view, it will be allowed.
997     * {@hide}
998     */
999    static final int PARENT_SAVE_DISABLED = 0x20000000;
1000
1001    /**
1002     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1003     * {@hide}
1004     */
1005    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1006
1007    /**
1008     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1009     * should add all focusable Views regardless if they are focusable in touch mode.
1010     */
1011    public static final int FOCUSABLES_ALL = 0x00000000;
1012
1013    /**
1014     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1015     * should add only Views focusable in touch mode.
1016     */
1017    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1018
1019    /**
1020     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1021     * item.
1022     */
1023    public static final int FOCUS_BACKWARD = 0x00000001;
1024
1025    /**
1026     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1027     * item.
1028     */
1029    public static final int FOCUS_FORWARD = 0x00000002;
1030
1031    /**
1032     * Use with {@link #focusSearch(int)}. Move focus to the left.
1033     */
1034    public static final int FOCUS_LEFT = 0x00000011;
1035
1036    /**
1037     * Use with {@link #focusSearch(int)}. Move focus up.
1038     */
1039    public static final int FOCUS_UP = 0x00000021;
1040
1041    /**
1042     * Use with {@link #focusSearch(int)}. Move focus to the right.
1043     */
1044    public static final int FOCUS_RIGHT = 0x00000042;
1045
1046    /**
1047     * Use with {@link #focusSearch(int)}. Move focus down.
1048     */
1049    public static final int FOCUS_DOWN = 0x00000082;
1050
1051    /**
1052     * Bits of {@link #getMeasuredWidthAndState()} and
1053     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1054     */
1055    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1056
1057    /**
1058     * Bits of {@link #getMeasuredWidthAndState()} and
1059     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1060     */
1061    public static final int MEASURED_STATE_MASK = 0xff000000;
1062
1063    /**
1064     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1065     * for functions that combine both width and height into a single int,
1066     * such as {@link #getMeasuredState()} and the childState argument of
1067     * {@link #resolveSizeAndState(int, int, int)}.
1068     */
1069    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1070
1071    /**
1072     * Bit of {@link #getMeasuredWidthAndState()} and
1073     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1074     * is smaller that the space the view would like to have.
1075     */
1076    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1077
1078    /**
1079     * Base View state sets
1080     */
1081    // Singles
1082    /**
1083     * Indicates the view has no states set. 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[] EMPTY_STATE_SET;
1091    /**
1092     * Indicates the view is enabled. 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[] ENABLED_STATE_SET;
1100    /**
1101     * Indicates the view is focused. 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[] FOCUSED_STATE_SET;
1109    /**
1110     * Indicates the view is selected. 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     */
1117    protected static final int[] SELECTED_STATE_SET;
1118    /**
1119     * Indicates the view is pressed. States are used with
1120     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1121     * view depending on its state.
1122     *
1123     * @see android.graphics.drawable.Drawable
1124     * @see #getDrawableState()
1125     * @hide
1126     */
1127    protected static final int[] PRESSED_STATE_SET;
1128    /**
1129     * Indicates the view's window has focus. States are used with
1130     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1131     * view depending on its state.
1132     *
1133     * @see android.graphics.drawable.Drawable
1134     * @see #getDrawableState()
1135     */
1136    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1137    // Doubles
1138    /**
1139     * Indicates the view is enabled and has the focus.
1140     *
1141     * @see #ENABLED_STATE_SET
1142     * @see #FOCUSED_STATE_SET
1143     */
1144    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1145    /**
1146     * Indicates the view is enabled and selected.
1147     *
1148     * @see #ENABLED_STATE_SET
1149     * @see #SELECTED_STATE_SET
1150     */
1151    protected static final int[] ENABLED_SELECTED_STATE_SET;
1152    /**
1153     * Indicates the view is enabled and that its window has focus.
1154     *
1155     * @see #ENABLED_STATE_SET
1156     * @see #WINDOW_FOCUSED_STATE_SET
1157     */
1158    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1159    /**
1160     * Indicates the view is focused and selected.
1161     *
1162     * @see #FOCUSED_STATE_SET
1163     * @see #SELECTED_STATE_SET
1164     */
1165    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1166    /**
1167     * Indicates the view has the focus and that its window has the focus.
1168     *
1169     * @see #FOCUSED_STATE_SET
1170     * @see #WINDOW_FOCUSED_STATE_SET
1171     */
1172    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1173    /**
1174     * Indicates the view is selected and that its window has the focus.
1175     *
1176     * @see #SELECTED_STATE_SET
1177     * @see #WINDOW_FOCUSED_STATE_SET
1178     */
1179    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1180    // Triples
1181    /**
1182     * Indicates the view is enabled, focused and selected.
1183     *
1184     * @see #ENABLED_STATE_SET
1185     * @see #FOCUSED_STATE_SET
1186     * @see #SELECTED_STATE_SET
1187     */
1188    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1189    /**
1190     * Indicates the view is enabled, focused and its window has the focus.
1191     *
1192     * @see #ENABLED_STATE_SET
1193     * @see #FOCUSED_STATE_SET
1194     * @see #WINDOW_FOCUSED_STATE_SET
1195     */
1196    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1197    /**
1198     * Indicates the view is enabled, selected and its window has the focus.
1199     *
1200     * @see #ENABLED_STATE_SET
1201     * @see #SELECTED_STATE_SET
1202     * @see #WINDOW_FOCUSED_STATE_SET
1203     */
1204    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1205    /**
1206     * Indicates the view is focused, selected and its window has the focus.
1207     *
1208     * @see #FOCUSED_STATE_SET
1209     * @see #SELECTED_STATE_SET
1210     * @see #WINDOW_FOCUSED_STATE_SET
1211     */
1212    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1213    /**
1214     * Indicates the view is enabled, focused, selected and its window
1215     * has the focus.
1216     *
1217     * @see #ENABLED_STATE_SET
1218     * @see #FOCUSED_STATE_SET
1219     * @see #SELECTED_STATE_SET
1220     * @see #WINDOW_FOCUSED_STATE_SET
1221     */
1222    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1223    /**
1224     * Indicates the view is pressed and its window has the focus.
1225     *
1226     * @see #PRESSED_STATE_SET
1227     * @see #WINDOW_FOCUSED_STATE_SET
1228     */
1229    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1230    /**
1231     * Indicates the view is pressed and selected.
1232     *
1233     * @see #PRESSED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     */
1236    protected static final int[] PRESSED_SELECTED_STATE_SET;
1237    /**
1238     * Indicates the view is pressed, selected and its window has the focus.
1239     *
1240     * @see #PRESSED_STATE_SET
1241     * @see #SELECTED_STATE_SET
1242     * @see #WINDOW_FOCUSED_STATE_SET
1243     */
1244    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is pressed and focused.
1247     *
1248     * @see #PRESSED_STATE_SET
1249     * @see #FOCUSED_STATE_SET
1250     */
1251    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1252    /**
1253     * Indicates the view is pressed, focused and its window has the focus.
1254     *
1255     * @see #PRESSED_STATE_SET
1256     * @see #FOCUSED_STATE_SET
1257     * @see #WINDOW_FOCUSED_STATE_SET
1258     */
1259    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1260    /**
1261     * Indicates the view is pressed, focused and selected.
1262     *
1263     * @see #PRESSED_STATE_SET
1264     * @see #SELECTED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     */
1267    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1268    /**
1269     * Indicates the view is pressed, focused, selected and its window has the focus.
1270     *
1271     * @see #PRESSED_STATE_SET
1272     * @see #FOCUSED_STATE_SET
1273     * @see #SELECTED_STATE_SET
1274     * @see #WINDOW_FOCUSED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed and enabled.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #ENABLED_STATE_SET
1282     */
1283    protected static final int[] PRESSED_ENABLED_STATE_SET;
1284    /**
1285     * Indicates the view is pressed, enabled and its window has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #ENABLED_STATE_SET
1289     * @see #WINDOW_FOCUSED_STATE_SET
1290     */
1291    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1292    /**
1293     * Indicates the view is pressed, enabled and selected.
1294     *
1295     * @see #PRESSED_STATE_SET
1296     * @see #ENABLED_STATE_SET
1297     * @see #SELECTED_STATE_SET
1298     */
1299    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1300    /**
1301     * Indicates the view is pressed, enabled, selected and its window has the
1302     * focus.
1303     *
1304     * @see #PRESSED_STATE_SET
1305     * @see #ENABLED_STATE_SET
1306     * @see #SELECTED_STATE_SET
1307     * @see #WINDOW_FOCUSED_STATE_SET
1308     */
1309    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1310    /**
1311     * Indicates the view is pressed, enabled and focused.
1312     *
1313     * @see #PRESSED_STATE_SET
1314     * @see #ENABLED_STATE_SET
1315     * @see #FOCUSED_STATE_SET
1316     */
1317    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1318    /**
1319     * Indicates the view is pressed, enabled, focused and its window has the
1320     * focus.
1321     *
1322     * @see #PRESSED_STATE_SET
1323     * @see #ENABLED_STATE_SET
1324     * @see #FOCUSED_STATE_SET
1325     * @see #WINDOW_FOCUSED_STATE_SET
1326     */
1327    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1328    /**
1329     * Indicates the view is pressed, enabled, focused and selected.
1330     *
1331     * @see #PRESSED_STATE_SET
1332     * @see #ENABLED_STATE_SET
1333     * @see #SELECTED_STATE_SET
1334     * @see #FOCUSED_STATE_SET
1335     */
1336    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1337    /**
1338     * Indicates the view is pressed, enabled, focused, selected and its window
1339     * has the focus.
1340     *
1341     * @see #PRESSED_STATE_SET
1342     * @see #ENABLED_STATE_SET
1343     * @see #SELECTED_STATE_SET
1344     * @see #FOCUSED_STATE_SET
1345     * @see #WINDOW_FOCUSED_STATE_SET
1346     */
1347    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1348
1349    /**
1350     * The order here is very important to {@link #getDrawableState()}
1351     */
1352    private static final int[][] VIEW_STATE_SETS;
1353
1354    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1355    static final int VIEW_STATE_SELECTED = 1 << 1;
1356    static final int VIEW_STATE_FOCUSED = 1 << 2;
1357    static final int VIEW_STATE_ENABLED = 1 << 3;
1358    static final int VIEW_STATE_PRESSED = 1 << 4;
1359    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1360    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1361    static final int VIEW_STATE_HOVERED = 1 << 7;
1362    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1363    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1364
1365    static final int[] VIEW_STATE_IDS = new int[] {
1366        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1367        R.attr.state_selected,          VIEW_STATE_SELECTED,
1368        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1369        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1370        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1371        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1372        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1373        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1374        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1375        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED
1376    };
1377
1378    static {
1379        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1380            throw new IllegalStateException(
1381                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1382        }
1383        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1384        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1385            int viewState = R.styleable.ViewDrawableStates[i];
1386            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1387                if (VIEW_STATE_IDS[j] == viewState) {
1388                    orderedIds[i * 2] = viewState;
1389                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1390                }
1391            }
1392        }
1393        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1394        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1395        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1396            int numBits = Integer.bitCount(i);
1397            int[] set = new int[numBits];
1398            int pos = 0;
1399            for (int j = 0; j < orderedIds.length; j += 2) {
1400                if ((i & orderedIds[j+1]) != 0) {
1401                    set[pos++] = orderedIds[j];
1402                }
1403            }
1404            VIEW_STATE_SETS[i] = set;
1405        }
1406
1407        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1408        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1409        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1410        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1412        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1413        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1415        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1417        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1419                | VIEW_STATE_FOCUSED];
1420        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1421        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1423        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1425        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1427                | VIEW_STATE_ENABLED];
1428        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1429                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1430        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1431                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1432                | VIEW_STATE_ENABLED];
1433        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1434                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1435                | VIEW_STATE_ENABLED];
1436        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1438                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1439
1440        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1441        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1443        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1445        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1447                | VIEW_STATE_PRESSED];
1448        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1449                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1450        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1452                | VIEW_STATE_PRESSED];
1453        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1455                | VIEW_STATE_PRESSED];
1456        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1457                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1458                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1459        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1460                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1461        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1463                | VIEW_STATE_PRESSED];
1464        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1466                | VIEW_STATE_PRESSED];
1467        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1469                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1470        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1472                | VIEW_STATE_PRESSED];
1473        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1475                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1476        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1477                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1478                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1479        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1480                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1481                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1482                | VIEW_STATE_PRESSED];
1483    }
1484
1485    /**
1486     * Accessibility event types that are dispatched for text population.
1487     */
1488    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1489            AccessibilityEvent.TYPE_VIEW_CLICKED
1490            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1491            | AccessibilityEvent.TYPE_VIEW_SELECTED
1492            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1493            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1494            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1495            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1496            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1497            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
1499            | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY;
1500
1501    /**
1502     * Temporary Rect currently for use in setBackground().  This will probably
1503     * be extended in the future to hold our own class with more than just
1504     * a Rect. :)
1505     */
1506    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1507
1508    /**
1509     * Map used to store views' tags.
1510     */
1511    private SparseArray<Object> mKeyedTags;
1512
1513    /**
1514     * The next available accessibility id.
1515     */
1516    private static int sNextAccessibilityViewId;
1517
1518    /**
1519     * The animation currently associated with this view.
1520     * @hide
1521     */
1522    protected Animation mCurrentAnimation = null;
1523
1524    /**
1525     * Width as measured during measure pass.
1526     * {@hide}
1527     */
1528    @ViewDebug.ExportedProperty(category = "measurement")
1529    int mMeasuredWidth;
1530
1531    /**
1532     * Height as measured during measure pass.
1533     * {@hide}
1534     */
1535    @ViewDebug.ExportedProperty(category = "measurement")
1536    int mMeasuredHeight;
1537
1538    /**
1539     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1540     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1541     * its display list. This flag, used only when hw accelerated, allows us to clear the
1542     * flag while retaining this information until it's needed (at getDisplayList() time and
1543     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1544     *
1545     * {@hide}
1546     */
1547    boolean mRecreateDisplayList = false;
1548
1549    /**
1550     * The view's identifier.
1551     * {@hide}
1552     *
1553     * @see #setId(int)
1554     * @see #getId()
1555     */
1556    @ViewDebug.ExportedProperty(resolveId = true)
1557    int mID = NO_ID;
1558
1559    /**
1560     * The stable ID of this view for accessibility purposes.
1561     */
1562    int mAccessibilityViewId = NO_ID;
1563
1564    private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
1565
1566    /**
1567     * The view's tag.
1568     * {@hide}
1569     *
1570     * @see #setTag(Object)
1571     * @see #getTag()
1572     */
1573    protected Object mTag;
1574
1575    // for mPrivateFlags:
1576    /** {@hide} */
1577    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1578    /** {@hide} */
1579    static final int PFLAG_FOCUSED                     = 0x00000002;
1580    /** {@hide} */
1581    static final int PFLAG_SELECTED                    = 0x00000004;
1582    /** {@hide} */
1583    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1584    /** {@hide} */
1585    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1586    /** {@hide} */
1587    static final int PFLAG_DRAWN                       = 0x00000020;
1588    /**
1589     * When this flag is set, this view is running an animation on behalf of its
1590     * children and should therefore not cancel invalidate requests, even if they
1591     * lie outside of this view's bounds.
1592     *
1593     * {@hide}
1594     */
1595    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1596    /** {@hide} */
1597    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1598    /** {@hide} */
1599    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1600    /** {@hide} */
1601    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1602    /** {@hide} */
1603    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1604    /** {@hide} */
1605    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1606    /** {@hide} */
1607    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1608    /** {@hide} */
1609    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1610
1611    private static final int PFLAG_PRESSED             = 0x00004000;
1612
1613    /** {@hide} */
1614    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1615    /**
1616     * Flag used to indicate that this view should be drawn once more (and only once
1617     * more) after its animation has completed.
1618     * {@hide}
1619     */
1620    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1621
1622    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1623
1624    /**
1625     * Indicates that the View returned true when onSetAlpha() was called and that
1626     * the alpha must be restored.
1627     * {@hide}
1628     */
1629    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1630
1631    /**
1632     * Set by {@link #setScrollContainer(boolean)}.
1633     */
1634    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1635
1636    /**
1637     * Set by {@link #setScrollContainer(boolean)}.
1638     */
1639    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1640
1641    /**
1642     * View flag indicating whether this view was invalidated (fully or partially.)
1643     *
1644     * @hide
1645     */
1646    static final int PFLAG_DIRTY                       = 0x00200000;
1647
1648    /**
1649     * View flag indicating whether this view was invalidated by an opaque
1650     * invalidate request.
1651     *
1652     * @hide
1653     */
1654    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1655
1656    /**
1657     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1658     *
1659     * @hide
1660     */
1661    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1662
1663    /**
1664     * Indicates whether the background is opaque.
1665     *
1666     * @hide
1667     */
1668    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1669
1670    /**
1671     * Indicates whether the scrollbars are opaque.
1672     *
1673     * @hide
1674     */
1675    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1676
1677    /**
1678     * Indicates whether the view is opaque.
1679     *
1680     * @hide
1681     */
1682    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1683
1684    /**
1685     * Indicates a prepressed state;
1686     * the short time between ACTION_DOWN and recognizing
1687     * a 'real' press. Prepressed is used to recognize quick taps
1688     * even when they are shorter than ViewConfiguration.getTapTimeout().
1689     *
1690     * @hide
1691     */
1692    private static final int PFLAG_PREPRESSED          = 0x02000000;
1693
1694    /**
1695     * Indicates whether the view is temporarily detached.
1696     *
1697     * @hide
1698     */
1699    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1700
1701    /**
1702     * Indicates that we should awaken scroll bars once attached
1703     *
1704     * @hide
1705     */
1706    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1707
1708    /**
1709     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1710     * @hide
1711     */
1712    private static final int PFLAG_HOVERED             = 0x10000000;
1713
1714    /**
1715     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1716     * for transform operations
1717     *
1718     * @hide
1719     */
1720    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1721
1722    /** {@hide} */
1723    static final int PFLAG_ACTIVATED                   = 0x40000000;
1724
1725    /**
1726     * Indicates that this view was specifically invalidated, not just dirtied because some
1727     * child view was invalidated. The flag is used to determine when we need to recreate
1728     * a view's display list (as opposed to just returning a reference to its existing
1729     * display list).
1730     *
1731     * @hide
1732     */
1733    static final int PFLAG_INVALIDATED                 = 0x80000000;
1734
1735    /**
1736     * Masks for mPrivateFlags2, as generated by dumpFlags():
1737     *
1738     * -------|-------|-------|-------|
1739     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1740     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1741     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1742     *                               1  PFLAG2_DRAG_HOVERED
1743     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1744     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1745     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1746     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1747     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1748     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1749     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1750     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1751     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1752     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1753     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1754     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1755     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1756     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1757     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1758     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1759     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1760     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1761     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1762     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1763     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1764     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1765     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1766     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1767     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1768     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1769     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1770     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1771     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1772     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1773     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1774     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1775     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1776     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1777     *   1                              PFLAG2_PADDING_RESOLVED
1778     * -------|-------|-------|-------|
1779     */
1780
1781    /**
1782     * Indicates that this view has reported that it can accept the current drag's content.
1783     * Cleared when the drag operation concludes.
1784     * @hide
1785     */
1786    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1787
1788    /**
1789     * Indicates that this view is currently directly under the drag location in a
1790     * drag-and-drop operation involving content that it can accept.  Cleared when
1791     * the drag exits the view, or when the drag operation concludes.
1792     * @hide
1793     */
1794    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1795
1796    /**
1797     * Horizontal layout direction of this view is from Left to Right.
1798     * Use with {@link #setLayoutDirection}.
1799     */
1800    public static final int LAYOUT_DIRECTION_LTR = 0;
1801
1802    /**
1803     * Horizontal layout direction of this view is from Right to Left.
1804     * Use with {@link #setLayoutDirection}.
1805     */
1806    public static final int LAYOUT_DIRECTION_RTL = 1;
1807
1808    /**
1809     * Horizontal layout direction of this view is inherited from its parent.
1810     * Use with {@link #setLayoutDirection}.
1811     */
1812    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1813
1814    /**
1815     * Horizontal layout direction of this view is from deduced from the default language
1816     * script for the locale. Use with {@link #setLayoutDirection}.
1817     */
1818    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1819
1820    /**
1821     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1822     * @hide
1823     */
1824    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1825
1826    /**
1827     * Mask for use with private flags indicating bits used for horizontal layout direction.
1828     * @hide
1829     */
1830    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1831
1832    /**
1833     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1834     * right-to-left direction.
1835     * @hide
1836     */
1837    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1838
1839    /**
1840     * Indicates whether the view horizontal layout direction has been resolved.
1841     * @hide
1842     */
1843    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1844
1845    /**
1846     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1847     * @hide
1848     */
1849    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1850            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1851
1852    /*
1853     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1854     * flag value.
1855     * @hide
1856     */
1857    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1858            LAYOUT_DIRECTION_LTR,
1859            LAYOUT_DIRECTION_RTL,
1860            LAYOUT_DIRECTION_INHERIT,
1861            LAYOUT_DIRECTION_LOCALE
1862    };
1863
1864    /**
1865     * Default horizontal layout direction.
1866     */
1867    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1868
1869    /**
1870     * Default horizontal layout direction.
1871     * @hide
1872     */
1873    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1874
1875    /**
1876     * Indicates that the view is tracking some sort of transient state
1877     * that the app should not need to be aware of, but that the framework
1878     * should take special care to preserve.
1879     *
1880     * @hide
1881     */
1882    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1883
1884    /**
1885     * Text direction is inherited thru {@link ViewGroup}
1886     */
1887    public static final int TEXT_DIRECTION_INHERIT = 0;
1888
1889    /**
1890     * Text direction is using "first strong algorithm". The first strong directional character
1891     * determines the paragraph direction. If there is no strong directional character, the
1892     * paragraph direction is the view's resolved layout direction.
1893     */
1894    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1895
1896    /**
1897     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1898     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1899     * If there are neither, the paragraph direction is the view's resolved layout direction.
1900     */
1901    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1902
1903    /**
1904     * Text direction is forced to LTR.
1905     */
1906    public static final int TEXT_DIRECTION_LTR = 3;
1907
1908    /**
1909     * Text direction is forced to RTL.
1910     */
1911    public static final int TEXT_DIRECTION_RTL = 4;
1912
1913    /**
1914     * Text direction is coming from the system Locale.
1915     */
1916    public static final int TEXT_DIRECTION_LOCALE = 5;
1917
1918    /**
1919     * Default text direction is inherited
1920     */
1921    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1922
1923    /**
1924     * Default resolved text direction
1925     * @hide
1926     */
1927    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1928
1929    /**
1930     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1931     * @hide
1932     */
1933    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1934
1935    /**
1936     * Mask for use with private flags indicating bits used for text direction.
1937     * @hide
1938     */
1939    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1940            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1941
1942    /**
1943     * Array of text direction flags for mapping attribute "textDirection" to correct
1944     * flag value.
1945     * @hide
1946     */
1947    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1948            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1949            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1950            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1951            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1952            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1954    };
1955
1956    /**
1957     * Indicates whether the view text direction has been resolved.
1958     * @hide
1959     */
1960    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1961            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1962
1963    /**
1964     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1965     * @hide
1966     */
1967    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1968
1969    /**
1970     * Mask for use with private flags indicating bits used for resolved text direction.
1971     * @hide
1972     */
1973    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1974            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1975
1976    /**
1977     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1978     * @hide
1979     */
1980    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1981            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1982
1983    /*
1984     * Default text alignment. The text alignment of this View is inherited from its parent.
1985     * Use with {@link #setTextAlignment(int)}
1986     */
1987    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1988
1989    /**
1990     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1991     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1992     *
1993     * Use with {@link #setTextAlignment(int)}
1994     */
1995    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1996
1997    /**
1998     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1999     *
2000     * Use with {@link #setTextAlignment(int)}
2001     */
2002    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2003
2004    /**
2005     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2006     *
2007     * Use with {@link #setTextAlignment(int)}
2008     */
2009    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2010
2011    /**
2012     * Center the paragraph, e.g. ALIGN_CENTER.
2013     *
2014     * Use with {@link #setTextAlignment(int)}
2015     */
2016    public static final int TEXT_ALIGNMENT_CENTER = 4;
2017
2018    /**
2019     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2020     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2021     *
2022     * Use with {@link #setTextAlignment(int)}
2023     */
2024    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2025
2026    /**
2027     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2028     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2029     *
2030     * Use with {@link #setTextAlignment(int)}
2031     */
2032    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2033
2034    /**
2035     * Default text alignment is inherited
2036     */
2037    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2038
2039    /**
2040     * Default resolved text alignment
2041     * @hide
2042     */
2043    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2044
2045    /**
2046      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2047      * @hide
2048      */
2049    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2050
2051    /**
2052      * Mask for use with private flags indicating bits used for text alignment.
2053      * @hide
2054      */
2055    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2056
2057    /**
2058     * Array of text direction flags for mapping attribute "textAlignment" to correct
2059     * flag value.
2060     * @hide
2061     */
2062    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2063            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2064            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2065            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2066            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2067            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2070    };
2071
2072    /**
2073     * Indicates whether the view text alignment has been resolved.
2074     * @hide
2075     */
2076    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2077
2078    /**
2079     * Bit shift to get the resolved text alignment.
2080     * @hide
2081     */
2082    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2083
2084    /**
2085     * Mask for use with private flags indicating bits used for text alignment.
2086     * @hide
2087     */
2088    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2089            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2090
2091    /**
2092     * Indicates whether if the view text alignment has been resolved to gravity
2093     */
2094    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2095            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2096
2097    // Accessiblity constants for mPrivateFlags2
2098
2099    /**
2100     * Shift for the bits in {@link #mPrivateFlags2} related to the
2101     * "importantForAccessibility" attribute.
2102     */
2103    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2104
2105    /**
2106     * Automatically determine whether a view is important for accessibility.
2107     */
2108    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2109
2110    /**
2111     * The view is important for accessibility.
2112     */
2113    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2114
2115    /**
2116     * The view is not important for accessibility.
2117     */
2118    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2119
2120    /**
2121     * The default whether the view is important for accessibility.
2122     */
2123    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2124
2125    /**
2126     * Mask for obtainig the bits which specify how to determine
2127     * whether a view is important for accessibility.
2128     */
2129    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2130        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2131        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2132
2133    /**
2134     * Flag indicating whether a view has accessibility focus.
2135     */
2136    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2137
2138    /**
2139     * Flag indicating whether a view state for accessibility has changed.
2140     */
2141    static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080
2142            << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2143
2144    /**
2145     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2146     * is used to check whether later changes to the view's transform should invalidate the
2147     * view to force the quickReject test to run again.
2148     */
2149    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2150
2151    /**
2152     * Flag indicating that start/end padding has been resolved into left/right padding
2153     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2154     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2155     * during measurement. In some special cases this is required such as when an adapter-based
2156     * view measures prospective children without attaching them to a window.
2157     */
2158    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2159
2160    /**
2161     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2162     */
2163    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2164
2165    /**
2166     * Group of bits indicating that RTL properties resolution is done.
2167     */
2168    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2169            PFLAG2_TEXT_DIRECTION_RESOLVED |
2170            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2171            PFLAG2_PADDING_RESOLVED |
2172            PFLAG2_DRAWABLE_RESOLVED;
2173
2174    // There are a couple of flags left in mPrivateFlags2
2175
2176    /* End of masks for mPrivateFlags2 */
2177
2178    /* Masks for mPrivateFlags3 */
2179
2180    /**
2181     * Flag indicating that view has a transform animation set on it. This is used to track whether
2182     * an animation is cleared between successive frames, in order to tell the associated
2183     * DisplayList to clear its animation matrix.
2184     */
2185    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2186
2187    /**
2188     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2189     * animation is cleared between successive frames, in order to tell the associated
2190     * DisplayList to restore its alpha value.
2191     */
2192    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2193
2194
2195    /* End of masks for mPrivateFlags3 */
2196
2197    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2198
2199    /**
2200     * Always allow a user to over-scroll this view, provided it is a
2201     * view that can scroll.
2202     *
2203     * @see #getOverScrollMode()
2204     * @see #setOverScrollMode(int)
2205     */
2206    public static final int OVER_SCROLL_ALWAYS = 0;
2207
2208    /**
2209     * Allow a user to over-scroll this view only if the content is large
2210     * enough to meaningfully scroll, provided it is a view that can scroll.
2211     *
2212     * @see #getOverScrollMode()
2213     * @see #setOverScrollMode(int)
2214     */
2215    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2216
2217    /**
2218     * Never allow a user to over-scroll this view.
2219     *
2220     * @see #getOverScrollMode()
2221     * @see #setOverScrollMode(int)
2222     */
2223    public static final int OVER_SCROLL_NEVER = 2;
2224
2225    /**
2226     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2227     * requested the system UI (status bar) to be visible (the default).
2228     *
2229     * @see #setSystemUiVisibility(int)
2230     */
2231    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2232
2233    /**
2234     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2235     * system UI to enter an unobtrusive "low profile" mode.
2236     *
2237     * <p>This is for use in games, book readers, video players, or any other
2238     * "immersive" application where the usual system chrome is deemed too distracting.
2239     *
2240     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2241     *
2242     * @see #setSystemUiVisibility(int)
2243     */
2244    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2245
2246    /**
2247     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2248     * system navigation be temporarily hidden.
2249     *
2250     * <p>This is an even less obtrusive state than that called for by
2251     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2252     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2253     * those to disappear. This is useful (in conjunction with the
2254     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2255     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2256     * window flags) for displaying content using every last pixel on the display.
2257     *
2258     * <p>There is a limitation: because navigation controls are so important, the least user
2259     * interaction will cause them to reappear immediately.  When this happens, both
2260     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2261     * so that both elements reappear at the same time.
2262     *
2263     * @see #setSystemUiVisibility(int)
2264     */
2265    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2266
2267    /**
2268     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2269     * into the normal fullscreen mode so that its content can take over the screen
2270     * while still allowing the user to interact with the application.
2271     *
2272     * <p>This has the same visual effect as
2273     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2274     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2275     * meaning that non-critical screen decorations (such as the status bar) will be
2276     * hidden while the user is in the View's window, focusing the experience on
2277     * that content.  Unlike the window flag, if you are using ActionBar in
2278     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2279     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2280     * hide the action bar.
2281     *
2282     * <p>This approach to going fullscreen is best used over the window flag when
2283     * it is a transient state -- that is, the application does this at certain
2284     * points in its user interaction where it wants to allow the user to focus
2285     * on content, but not as a continuous state.  For situations where the application
2286     * would like to simply stay full screen the entire time (such as a game that
2287     * wants to take over the screen), the
2288     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2289     * is usually a better approach.  The state set here will be removed by the system
2290     * in various situations (such as the user moving to another application) like
2291     * the other system UI states.
2292     *
2293     * <p>When using this flag, the application should provide some easy facility
2294     * for the user to go out of it.  A common example would be in an e-book
2295     * reader, where tapping on the screen brings back whatever screen and UI
2296     * decorations that had been hidden while the user was immersed in reading
2297     * the book.
2298     *
2299     * @see #setSystemUiVisibility(int)
2300     */
2301    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2302
2303    /**
2304     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2305     * flags, we would like a stable view of the content insets given to
2306     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2307     * will always represent the worst case that the application can expect
2308     * as a continuous state.  In the stock Android UI this is the space for
2309     * the system bar, nav bar, and status bar, but not more transient elements
2310     * such as an input method.
2311     *
2312     * The stable layout your UI sees is based on the system UI modes you can
2313     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2314     * then you will get a stable layout for changes of the
2315     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2316     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2317     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2318     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2319     * with a stable layout.  (Note that you should avoid using
2320     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2321     *
2322     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2323     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2324     * then a hidden status bar will be considered a "stable" state for purposes
2325     * here.  This allows your UI to continually hide the status bar, while still
2326     * using the system UI flags to hide the action bar while still retaining
2327     * a stable layout.  Note that changing the window fullscreen flag will never
2328     * provide a stable layout for a clean transition.
2329     *
2330     * <p>If you are using ActionBar in
2331     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2332     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2333     * insets it adds to those given to the application.
2334     */
2335    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2336
2337    /**
2338     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2339     * to be layed out as if it has requested
2340     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2341     * allows it to avoid artifacts when switching in and out of that mode, at
2342     * the expense that some of its user interface may be covered by screen
2343     * decorations when they are shown.  You can perform layout of your inner
2344     * UI elements to account for the navigation system UI through the
2345     * {@link #fitSystemWindows(Rect)} method.
2346     */
2347    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2348
2349    /**
2350     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2351     * to be layed out as if it has requested
2352     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2353     * allows it to avoid artifacts when switching in and out of that mode, at
2354     * the expense that some of its user interface may be covered by screen
2355     * decorations when they are shown.  You can perform layout of your inner
2356     * UI elements to account for non-fullscreen system UI through the
2357     * {@link #fitSystemWindows(Rect)} method.
2358     */
2359    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2360
2361    /**
2362     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2363     */
2364    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2365
2366    /**
2367     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2368     */
2369    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2370
2371    /**
2372     * @hide
2373     *
2374     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2375     * out of the public fields to keep the undefined bits out of the developer's way.
2376     *
2377     * Flag to make the status bar not expandable.  Unless you also
2378     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2379     */
2380    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2381
2382    /**
2383     * @hide
2384     *
2385     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2386     * out of the public fields to keep the undefined bits out of the developer's way.
2387     *
2388     * Flag to hide notification icons and scrolling ticker text.
2389     */
2390    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2391
2392    /**
2393     * @hide
2394     *
2395     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2396     * out of the public fields to keep the undefined bits out of the developer's way.
2397     *
2398     * Flag to disable incoming notification alerts.  This will not block
2399     * icons, but it will block sound, vibrating and other visual or aural notifications.
2400     */
2401    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2402
2403    /**
2404     * @hide
2405     *
2406     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2407     * out of the public fields to keep the undefined bits out of the developer's way.
2408     *
2409     * Flag to hide only the scrolling ticker.  Note that
2410     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2411     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2412     */
2413    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2414
2415    /**
2416     * @hide
2417     *
2418     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2419     * out of the public fields to keep the undefined bits out of the developer's way.
2420     *
2421     * Flag to hide the center system info area.
2422     */
2423    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2424
2425    /**
2426     * @hide
2427     *
2428     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2429     * out of the public fields to keep the undefined bits out of the developer's way.
2430     *
2431     * Flag to hide only the home button.  Don't use this
2432     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2433     */
2434    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2435
2436    /**
2437     * @hide
2438     *
2439     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2440     * out of the public fields to keep the undefined bits out of the developer's way.
2441     *
2442     * Flag to hide only the back button. Don't use this
2443     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2444     */
2445    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2446
2447    /**
2448     * @hide
2449     *
2450     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2451     * out of the public fields to keep the undefined bits out of the developer's way.
2452     *
2453     * Flag to hide only the clock.  You might use this if your activity has
2454     * its own clock making the status bar's clock redundant.
2455     */
2456    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2457
2458    /**
2459     * @hide
2460     *
2461     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2462     * out of the public fields to keep the undefined bits out of the developer's way.
2463     *
2464     * Flag to hide only the recent apps button. Don't use this
2465     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2466     */
2467    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2468
2469    /**
2470     * @hide
2471     *
2472     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2473     * out of the public fields to keep the undefined bits out of the developer's way.
2474     *
2475     * Flag to disable the global search gesture. Don't use this
2476     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2477     */
2478    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2479
2480    /**
2481     * @hide
2482     */
2483    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2484
2485    /**
2486     * These are the system UI flags that can be cleared by events outside
2487     * of an application.  Currently this is just the ability to tap on the
2488     * screen while hiding the navigation bar to have it return.
2489     * @hide
2490     */
2491    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2492            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2493            | SYSTEM_UI_FLAG_FULLSCREEN;
2494
2495    /**
2496     * Flags that can impact the layout in relation to system UI.
2497     */
2498    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2499            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2500            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2501
2502    /**
2503     * Find views that render the specified text.
2504     *
2505     * @see #findViewsWithText(ArrayList, CharSequence, int)
2506     */
2507    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2508
2509    /**
2510     * Find find views that contain the specified content description.
2511     *
2512     * @see #findViewsWithText(ArrayList, CharSequence, int)
2513     */
2514    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2515
2516    /**
2517     * Find views that contain {@link AccessibilityNodeProvider}. Such
2518     * a View is a root of virtual view hierarchy and may contain the searched
2519     * text. If this flag is set Views with providers are automatically
2520     * added and it is a responsibility of the client to call the APIs of
2521     * the provider to determine whether the virtual tree rooted at this View
2522     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2523     * represeting the virtual views with this text.
2524     *
2525     * @see #findViewsWithText(ArrayList, CharSequence, int)
2526     *
2527     * @hide
2528     */
2529    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2530
2531    /**
2532     * The undefined cursor position.
2533     *
2534     * @hide
2535     */
2536    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2537
2538    /**
2539     * Indicates that the screen has changed state and is now off.
2540     *
2541     * @see #onScreenStateChanged(int)
2542     */
2543    public static final int SCREEN_STATE_OFF = 0x0;
2544
2545    /**
2546     * Indicates that the screen has changed state and is now on.
2547     *
2548     * @see #onScreenStateChanged(int)
2549     */
2550    public static final int SCREEN_STATE_ON = 0x1;
2551
2552    /**
2553     * Controls the over-scroll mode for this view.
2554     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2555     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2556     * and {@link #OVER_SCROLL_NEVER}.
2557     */
2558    private int mOverScrollMode;
2559
2560    /**
2561     * The parent this view is attached to.
2562     * {@hide}
2563     *
2564     * @see #getParent()
2565     */
2566    protected ViewParent mParent;
2567
2568    /**
2569     * {@hide}
2570     */
2571    AttachInfo mAttachInfo;
2572
2573    /**
2574     * {@hide}
2575     */
2576    @ViewDebug.ExportedProperty(flagMapping = {
2577        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2578                name = "FORCE_LAYOUT"),
2579        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2580                name = "LAYOUT_REQUIRED"),
2581        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2582            name = "DRAWING_CACHE_INVALID", outputIf = false),
2583        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2584        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2585        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2586        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2587    })
2588    int mPrivateFlags;
2589    int mPrivateFlags2;
2590    int mPrivateFlags3;
2591
2592    /**
2593     * This view's request for the visibility of the status bar.
2594     * @hide
2595     */
2596    @ViewDebug.ExportedProperty(flagMapping = {
2597        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2598                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2599                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2600        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2601                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2602                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2603        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2604                                equals = SYSTEM_UI_FLAG_VISIBLE,
2605                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2606    })
2607    int mSystemUiVisibility;
2608
2609    /**
2610     * Reference count for transient state.
2611     * @see #setHasTransientState(boolean)
2612     */
2613    int mTransientStateCount = 0;
2614
2615    /**
2616     * Count of how many windows this view has been attached to.
2617     */
2618    int mWindowAttachCount;
2619
2620    /**
2621     * The layout parameters associated with this view and used by the parent
2622     * {@link android.view.ViewGroup} to determine how this view should be
2623     * laid out.
2624     * {@hide}
2625     */
2626    protected ViewGroup.LayoutParams mLayoutParams;
2627
2628    /**
2629     * The view flags hold various views states.
2630     * {@hide}
2631     */
2632    @ViewDebug.ExportedProperty
2633    int mViewFlags;
2634
2635    static class TransformationInfo {
2636        /**
2637         * The transform matrix for the View. This transform is calculated internally
2638         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2639         * is used by default. Do *not* use this variable directly; instead call
2640         * getMatrix(), which will automatically recalculate the matrix if necessary
2641         * to get the correct matrix based on the latest rotation and scale properties.
2642         */
2643        private final Matrix mMatrix = new Matrix();
2644
2645        /**
2646         * The transform matrix for the View. This transform is calculated internally
2647         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2648         * is used by default. Do *not* use this variable directly; instead call
2649         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2650         * to get the correct matrix based on the latest rotation and scale properties.
2651         */
2652        private Matrix mInverseMatrix;
2653
2654        /**
2655         * An internal variable that tracks whether we need to recalculate the
2656         * transform matrix, based on whether the rotation or scaleX/Y properties
2657         * have changed since the matrix was last calculated.
2658         */
2659        boolean mMatrixDirty = false;
2660
2661        /**
2662         * An internal variable that tracks whether we need to recalculate the
2663         * transform matrix, based on whether the rotation or scaleX/Y properties
2664         * have changed since the matrix was last calculated.
2665         */
2666        private boolean mInverseMatrixDirty = true;
2667
2668        /**
2669         * A variable that tracks whether we need to recalculate the
2670         * transform matrix, based on whether the rotation or scaleX/Y properties
2671         * have changed since the matrix was last calculated. This variable
2672         * is only valid after a call to updateMatrix() or to a function that
2673         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2674         */
2675        private boolean mMatrixIsIdentity = true;
2676
2677        /**
2678         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2679         */
2680        private Camera mCamera = null;
2681
2682        /**
2683         * This matrix is used when computing the matrix for 3D rotations.
2684         */
2685        private Matrix matrix3D = null;
2686
2687        /**
2688         * These prev values are used to recalculate a centered pivot point when necessary. The
2689         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2690         * set), so thes values are only used then as well.
2691         */
2692        private int mPrevWidth = -1;
2693        private int mPrevHeight = -1;
2694
2695        /**
2696         * The degrees rotation around the vertical axis through the pivot point.
2697         */
2698        @ViewDebug.ExportedProperty
2699        float mRotationY = 0f;
2700
2701        /**
2702         * The degrees rotation around the horizontal axis through the pivot point.
2703         */
2704        @ViewDebug.ExportedProperty
2705        float mRotationX = 0f;
2706
2707        /**
2708         * The degrees rotation around the pivot point.
2709         */
2710        @ViewDebug.ExportedProperty
2711        float mRotation = 0f;
2712
2713        /**
2714         * The amount of translation of the object away from its left property (post-layout).
2715         */
2716        @ViewDebug.ExportedProperty
2717        float mTranslationX = 0f;
2718
2719        /**
2720         * The amount of translation of the object away from its top property (post-layout).
2721         */
2722        @ViewDebug.ExportedProperty
2723        float mTranslationY = 0f;
2724
2725        /**
2726         * The amount of scale in the x direction around the pivot point. A
2727         * value of 1 means no scaling is applied.
2728         */
2729        @ViewDebug.ExportedProperty
2730        float mScaleX = 1f;
2731
2732        /**
2733         * The amount of scale in the y direction around the pivot point. A
2734         * value of 1 means no scaling is applied.
2735         */
2736        @ViewDebug.ExportedProperty
2737        float mScaleY = 1f;
2738
2739        /**
2740         * The x location of the point around which the view is rotated and scaled.
2741         */
2742        @ViewDebug.ExportedProperty
2743        float mPivotX = 0f;
2744
2745        /**
2746         * The y location of the point around which the view is rotated and scaled.
2747         */
2748        @ViewDebug.ExportedProperty
2749        float mPivotY = 0f;
2750
2751        /**
2752         * The opacity of the View. This is a value from 0 to 1, where 0 means
2753         * completely transparent and 1 means completely opaque.
2754         */
2755        @ViewDebug.ExportedProperty
2756        float mAlpha = 1f;
2757    }
2758
2759    TransformationInfo mTransformationInfo;
2760
2761    private boolean mLastIsOpaque;
2762
2763    /**
2764     * Convenience value to check for float values that are close enough to zero to be considered
2765     * zero.
2766     */
2767    private static final float NONZERO_EPSILON = .001f;
2768
2769    /**
2770     * The distance in pixels from the left edge of this view's parent
2771     * to the left edge of this view.
2772     * {@hide}
2773     */
2774    @ViewDebug.ExportedProperty(category = "layout")
2775    protected int mLeft;
2776    /**
2777     * The distance in pixels from the left edge of this view's parent
2778     * to the right edge of this view.
2779     * {@hide}
2780     */
2781    @ViewDebug.ExportedProperty(category = "layout")
2782    protected int mRight;
2783    /**
2784     * The distance in pixels from the top edge of this view's parent
2785     * to the top edge of this view.
2786     * {@hide}
2787     */
2788    @ViewDebug.ExportedProperty(category = "layout")
2789    protected int mTop;
2790    /**
2791     * The distance in pixels from the top edge of this view's parent
2792     * to the bottom edge of this view.
2793     * {@hide}
2794     */
2795    @ViewDebug.ExportedProperty(category = "layout")
2796    protected int mBottom;
2797
2798    /**
2799     * The offset, in pixels, by which the content of this view is scrolled
2800     * horizontally.
2801     * {@hide}
2802     */
2803    @ViewDebug.ExportedProperty(category = "scrolling")
2804    protected int mScrollX;
2805    /**
2806     * The offset, in pixels, by which the content of this view is scrolled
2807     * vertically.
2808     * {@hide}
2809     */
2810    @ViewDebug.ExportedProperty(category = "scrolling")
2811    protected int mScrollY;
2812
2813    /**
2814     * The left padding in pixels, that is the distance in pixels between the
2815     * left edge of this view and the left edge of its content.
2816     * {@hide}
2817     */
2818    @ViewDebug.ExportedProperty(category = "padding")
2819    protected int mPaddingLeft = 0;
2820    /**
2821     * The right padding in pixels, that is the distance in pixels between the
2822     * right edge of this view and the right edge of its content.
2823     * {@hide}
2824     */
2825    @ViewDebug.ExportedProperty(category = "padding")
2826    protected int mPaddingRight = 0;
2827    /**
2828     * The top padding in pixels, that is the distance in pixels between the
2829     * top edge of this view and the top edge of its content.
2830     * {@hide}
2831     */
2832    @ViewDebug.ExportedProperty(category = "padding")
2833    protected int mPaddingTop;
2834    /**
2835     * The bottom padding in pixels, that is the distance in pixels between the
2836     * bottom edge of this view and the bottom edge of its content.
2837     * {@hide}
2838     */
2839    @ViewDebug.ExportedProperty(category = "padding")
2840    protected int mPaddingBottom;
2841
2842    /**
2843     * The layout insets in pixels, that is the distance in pixels between the
2844     * visible edges of this view its bounds.
2845     */
2846    private Insets mLayoutInsets;
2847
2848    /**
2849     * Briefly describes the view and is primarily used for accessibility support.
2850     */
2851    private CharSequence mContentDescription;
2852
2853    /**
2854     * Specifies the id of a view for which this view serves as a label for
2855     * accessibility purposes.
2856     */
2857    private int mLabelForId = View.NO_ID;
2858
2859    /**
2860     * Predicate for matching labeled view id with its label for
2861     * accessibility purposes.
2862     */
2863    private MatchLabelForPredicate mMatchLabelForPredicate;
2864
2865    /**
2866     * Predicate for matching a view by its id.
2867     */
2868    private MatchIdPredicate mMatchIdPredicate;
2869
2870    /**
2871     * Cache the paddingRight set by the user to append to the scrollbar's size.
2872     *
2873     * @hide
2874     */
2875    @ViewDebug.ExportedProperty(category = "padding")
2876    protected int mUserPaddingRight;
2877
2878    /**
2879     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2880     *
2881     * @hide
2882     */
2883    @ViewDebug.ExportedProperty(category = "padding")
2884    protected int mUserPaddingBottom;
2885
2886    /**
2887     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2888     *
2889     * @hide
2890     */
2891    @ViewDebug.ExportedProperty(category = "padding")
2892    protected int mUserPaddingLeft;
2893
2894    /**
2895     * Cache the paddingStart set by the user to append to the scrollbar's size.
2896     *
2897     */
2898    @ViewDebug.ExportedProperty(category = "padding")
2899    int mUserPaddingStart;
2900
2901    /**
2902     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2903     *
2904     */
2905    @ViewDebug.ExportedProperty(category = "padding")
2906    int mUserPaddingEnd;
2907
2908    /**
2909     * Cache initial left padding.
2910     *
2911     * @hide
2912     */
2913    int mUserPaddingLeftInitial = 0;
2914
2915    /**
2916     * Cache initial right padding.
2917     *
2918     * @hide
2919     */
2920    int mUserPaddingRightInitial = 0;
2921
2922    /**
2923     * Default undefined padding
2924     */
2925    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2926
2927    /**
2928     * @hide
2929     */
2930    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2931    /**
2932     * @hide
2933     */
2934    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2935
2936    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
2937    private Drawable mBackground;
2938
2939    private int mBackgroundResource;
2940    private boolean mBackgroundSizeChanged;
2941
2942    static class ListenerInfo {
2943        /**
2944         * Listener used to dispatch focus change events.
2945         * This field should be made private, so it is hidden from the SDK.
2946         * {@hide}
2947         */
2948        protected OnFocusChangeListener mOnFocusChangeListener;
2949
2950        /**
2951         * Listeners for layout change events.
2952         */
2953        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2954
2955        /**
2956         * Listeners for attach events.
2957         */
2958        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2959
2960        /**
2961         * Listener used to dispatch click events.
2962         * This field should be made private, so it is hidden from the SDK.
2963         * {@hide}
2964         */
2965        public OnClickListener mOnClickListener;
2966
2967        /**
2968         * Listener used to dispatch long click events.
2969         * This field should be made private, so it is hidden from the SDK.
2970         * {@hide}
2971         */
2972        protected OnLongClickListener mOnLongClickListener;
2973
2974        /**
2975         * Listener used to build the context menu.
2976         * This field should be made private, so it is hidden from the SDK.
2977         * {@hide}
2978         */
2979        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2980
2981        private OnKeyListener mOnKeyListener;
2982
2983        private OnTouchListener mOnTouchListener;
2984
2985        private OnHoverListener mOnHoverListener;
2986
2987        private OnGenericMotionListener mOnGenericMotionListener;
2988
2989        private OnDragListener mOnDragListener;
2990
2991        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2992    }
2993
2994    ListenerInfo mListenerInfo;
2995
2996    /**
2997     * The application environment this view lives in.
2998     * This field should be made private, so it is hidden from the SDK.
2999     * {@hide}
3000     */
3001    protected Context mContext;
3002
3003    private final Resources mResources;
3004
3005    private ScrollabilityCache mScrollCache;
3006
3007    private int[] mDrawableState = null;
3008
3009    /**
3010     * Set to true when drawing cache is enabled and cannot be created.
3011     *
3012     * @hide
3013     */
3014    public boolean mCachingFailed;
3015
3016    private Bitmap mDrawingCache;
3017    private Bitmap mUnscaledDrawingCache;
3018    private HardwareLayer mHardwareLayer;
3019    DisplayList mDisplayList;
3020
3021    /**
3022     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3023     * the user may specify which view to go to next.
3024     */
3025    private int mNextFocusLeftId = View.NO_ID;
3026
3027    /**
3028     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3029     * the user may specify which view to go to next.
3030     */
3031    private int mNextFocusRightId = View.NO_ID;
3032
3033    /**
3034     * When this view has focus and the next focus is {@link #FOCUS_UP},
3035     * the user may specify which view to go to next.
3036     */
3037    private int mNextFocusUpId = View.NO_ID;
3038
3039    /**
3040     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3041     * the user may specify which view to go to next.
3042     */
3043    private int mNextFocusDownId = View.NO_ID;
3044
3045    /**
3046     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3047     * the user may specify which view to go to next.
3048     */
3049    int mNextFocusForwardId = View.NO_ID;
3050
3051    private CheckForLongPress mPendingCheckForLongPress;
3052    private CheckForTap mPendingCheckForTap = null;
3053    private PerformClick mPerformClick;
3054    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3055
3056    private UnsetPressedState mUnsetPressedState;
3057
3058    /**
3059     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3060     * up event while a long press is invoked as soon as the long press duration is reached, so
3061     * a long press could be performed before the tap is checked, in which case the tap's action
3062     * should not be invoked.
3063     */
3064    private boolean mHasPerformedLongPress;
3065
3066    /**
3067     * The minimum height of the view. We'll try our best to have the height
3068     * of this view to at least this amount.
3069     */
3070    @ViewDebug.ExportedProperty(category = "measurement")
3071    private int mMinHeight;
3072
3073    /**
3074     * The minimum width of the view. We'll try our best to have the width
3075     * of this view to at least this amount.
3076     */
3077    @ViewDebug.ExportedProperty(category = "measurement")
3078    private int mMinWidth;
3079
3080    /**
3081     * The delegate to handle touch events that are physically in this view
3082     * but should be handled by another view.
3083     */
3084    private TouchDelegate mTouchDelegate = null;
3085
3086    /**
3087     * Solid color to use as a background when creating the drawing cache. Enables
3088     * the cache to use 16 bit bitmaps instead of 32 bit.
3089     */
3090    private int mDrawingCacheBackgroundColor = 0;
3091
3092    /**
3093     * Special tree observer used when mAttachInfo is null.
3094     */
3095    private ViewTreeObserver mFloatingTreeObserver;
3096
3097    /**
3098     * Cache the touch slop from the context that created the view.
3099     */
3100    private int mTouchSlop;
3101
3102    /**
3103     * Object that handles automatic animation of view properties.
3104     */
3105    private ViewPropertyAnimator mAnimator = null;
3106
3107    /**
3108     * Flag indicating that a drag can cross window boundaries.  When
3109     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3110     * with this flag set, all visible applications will be able to participate
3111     * in the drag operation and receive the dragged content.
3112     *
3113     * @hide
3114     */
3115    public static final int DRAG_FLAG_GLOBAL = 1;
3116
3117    /**
3118     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3119     */
3120    private float mVerticalScrollFactor;
3121
3122    /**
3123     * Position of the vertical scroll bar.
3124     */
3125    private int mVerticalScrollbarPosition;
3126
3127    /**
3128     * Position the scroll bar at the default position as determined by the system.
3129     */
3130    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3131
3132    /**
3133     * Position the scroll bar along the left edge.
3134     */
3135    public static final int SCROLLBAR_POSITION_LEFT = 1;
3136
3137    /**
3138     * Position the scroll bar along the right edge.
3139     */
3140    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3141
3142    /**
3143     * Indicates that the view does not have a layer.
3144     *
3145     * @see #getLayerType()
3146     * @see #setLayerType(int, android.graphics.Paint)
3147     * @see #LAYER_TYPE_SOFTWARE
3148     * @see #LAYER_TYPE_HARDWARE
3149     */
3150    public static final int LAYER_TYPE_NONE = 0;
3151
3152    /**
3153     * <p>Indicates that the view has a software layer. A software layer is backed
3154     * by a bitmap and causes the view to be rendered using Android's software
3155     * rendering pipeline, even if hardware acceleration is enabled.</p>
3156     *
3157     * <p>Software layers have various usages:</p>
3158     * <p>When the application is not using hardware acceleration, a software layer
3159     * is useful to apply a specific color filter and/or blending mode and/or
3160     * translucency to a view and all its children.</p>
3161     * <p>When the application is using hardware acceleration, a software layer
3162     * is useful to render drawing primitives not supported by the hardware
3163     * accelerated pipeline. It can also be used to cache a complex view tree
3164     * into a texture and reduce the complexity of drawing operations. For instance,
3165     * when animating a complex view tree with a translation, a software layer can
3166     * be used to render the view tree only once.</p>
3167     * <p>Software layers should be avoided when the affected view tree updates
3168     * often. Every update will require to re-render the software layer, which can
3169     * potentially be slow (particularly when hardware acceleration is turned on
3170     * since the layer will have to be uploaded into a hardware texture after every
3171     * update.)</p>
3172     *
3173     * @see #getLayerType()
3174     * @see #setLayerType(int, android.graphics.Paint)
3175     * @see #LAYER_TYPE_NONE
3176     * @see #LAYER_TYPE_HARDWARE
3177     */
3178    public static final int LAYER_TYPE_SOFTWARE = 1;
3179
3180    /**
3181     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3182     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3183     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3184     * rendering pipeline, but only if hardware acceleration is turned on for the
3185     * view hierarchy. When hardware acceleration is turned off, hardware layers
3186     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3187     *
3188     * <p>A hardware layer is useful to apply a specific color filter and/or
3189     * blending mode and/or translucency to a view and all its children.</p>
3190     * <p>A hardware layer can be used to cache a complex view tree into a
3191     * texture and reduce the complexity of drawing operations. For instance,
3192     * when animating a complex view tree with a translation, a hardware layer can
3193     * be used to render the view tree only once.</p>
3194     * <p>A hardware layer can also be used to increase the rendering quality when
3195     * rotation transformations are applied on a view. It can also be used to
3196     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3197     *
3198     * @see #getLayerType()
3199     * @see #setLayerType(int, android.graphics.Paint)
3200     * @see #LAYER_TYPE_NONE
3201     * @see #LAYER_TYPE_SOFTWARE
3202     */
3203    public static final int LAYER_TYPE_HARDWARE = 2;
3204
3205    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3206            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3207            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3208            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3209    })
3210    int mLayerType = LAYER_TYPE_NONE;
3211    Paint mLayerPaint;
3212    Rect mLocalDirtyRect;
3213
3214    /**
3215     * Set to true when the view is sending hover accessibility events because it
3216     * is the innermost hovered view.
3217     */
3218    private boolean mSendingHoverAccessibilityEvents;
3219
3220    /**
3221     * Delegate for injecting accessibility functionality.
3222     */
3223    AccessibilityDelegate mAccessibilityDelegate;
3224
3225    /**
3226     * The view's overlay layer. Developers get a reference to the overlay via getOverlay()
3227     * and add/remove objects to/from the overlay directly through the Overlay methods.
3228     */
3229    ViewOverlay mOverlay;
3230
3231    /**
3232     * Consistency verifier for debugging purposes.
3233     * @hide
3234     */
3235    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3236            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3237                    new InputEventConsistencyVerifier(this, 0) : null;
3238
3239    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3240
3241    /**
3242     * Simple constructor to use when creating a view from code.
3243     *
3244     * @param context The Context the view is running in, through which it can
3245     *        access the current theme, resources, etc.
3246     */
3247    public View(Context context) {
3248        mContext = context;
3249        mResources = context != null ? context.getResources() : null;
3250        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3251        // Set some flags defaults
3252        mPrivateFlags2 =
3253                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3254                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3255                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3256                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3257                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3258                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3259        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3260        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3261        mUserPaddingStart = UNDEFINED_PADDING;
3262        mUserPaddingEnd = UNDEFINED_PADDING;
3263
3264        if (!sUseBrokenMakeMeasureSpec && context.getApplicationInfo().targetSdkVersion <=
3265                Build.VERSION_CODES.JELLY_BEAN_MR1 ) {
3266            // Older apps may need this compatibility hack for measurement.
3267            sUseBrokenMakeMeasureSpec = true;
3268        }
3269    }
3270
3271    /**
3272     * Constructor that is called when inflating a view from XML. This is called
3273     * when a view is being constructed from an XML file, supplying attributes
3274     * that were specified in the XML file. This version uses a default style of
3275     * 0, so the only attribute values applied are those in the Context's Theme
3276     * and the given AttributeSet.
3277     *
3278     * <p>
3279     * The method onFinishInflate() will be called after all children have been
3280     * added.
3281     *
3282     * @param context The Context the view is running in, through which it can
3283     *        access the current theme, resources, etc.
3284     * @param attrs The attributes of the XML tag that is inflating the view.
3285     * @see #View(Context, AttributeSet, int)
3286     */
3287    public View(Context context, AttributeSet attrs) {
3288        this(context, attrs, 0);
3289    }
3290
3291    /**
3292     * Perform inflation from XML and apply a class-specific base style. This
3293     * constructor of View allows subclasses to use their own base style when
3294     * they are inflating. For example, a Button class's constructor would call
3295     * this version of the super class constructor and supply
3296     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3297     * the theme's button style to modify all of the base view attributes (in
3298     * particular its background) as well as the Button class's attributes.
3299     *
3300     * @param context The Context the view is running in, through which it can
3301     *        access the current theme, resources, etc.
3302     * @param attrs The attributes of the XML tag that is inflating the view.
3303     * @param defStyle The default style to apply to this view. If 0, no style
3304     *        will be applied (beyond what is included in the theme). This may
3305     *        either be an attribute resource, whose value will be retrieved
3306     *        from the current theme, or an explicit style resource.
3307     * @see #View(Context, AttributeSet)
3308     */
3309    public View(Context context, AttributeSet attrs, int defStyle) {
3310        this(context);
3311
3312        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3313                defStyle, 0);
3314
3315        Drawable background = null;
3316
3317        int leftPadding = -1;
3318        int topPadding = -1;
3319        int rightPadding = -1;
3320        int bottomPadding = -1;
3321        int startPadding = UNDEFINED_PADDING;
3322        int endPadding = UNDEFINED_PADDING;
3323
3324        int padding = -1;
3325
3326        int viewFlagValues = 0;
3327        int viewFlagMasks = 0;
3328
3329        boolean setScrollContainer = false;
3330
3331        int x = 0;
3332        int y = 0;
3333
3334        float tx = 0;
3335        float ty = 0;
3336        float rotation = 0;
3337        float rotationX = 0;
3338        float rotationY = 0;
3339        float sx = 1f;
3340        float sy = 1f;
3341        boolean transformSet = false;
3342
3343        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3344        int overScrollMode = mOverScrollMode;
3345        boolean initializeScrollbars = false;
3346
3347        boolean leftPaddingDefined = false;
3348        boolean rightPaddingDefined = false;
3349        boolean startPaddingDefined = false;
3350        boolean endPaddingDefined = false;
3351
3352        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3353
3354        final int N = a.getIndexCount();
3355        for (int i = 0; i < N; i++) {
3356            int attr = a.getIndex(i);
3357            switch (attr) {
3358                case com.android.internal.R.styleable.View_background:
3359                    background = a.getDrawable(attr);
3360                    break;
3361                case com.android.internal.R.styleable.View_padding:
3362                    padding = a.getDimensionPixelSize(attr, -1);
3363                    mUserPaddingLeftInitial = padding;
3364                    mUserPaddingRightInitial = padding;
3365                    leftPaddingDefined = true;
3366                    rightPaddingDefined = true;
3367                    break;
3368                 case com.android.internal.R.styleable.View_paddingLeft:
3369                    leftPadding = a.getDimensionPixelSize(attr, -1);
3370                    mUserPaddingLeftInitial = leftPadding;
3371                    leftPaddingDefined = true;
3372                    break;
3373                case com.android.internal.R.styleable.View_paddingTop:
3374                    topPadding = a.getDimensionPixelSize(attr, -1);
3375                    break;
3376                case com.android.internal.R.styleable.View_paddingRight:
3377                    rightPadding = a.getDimensionPixelSize(attr, -1);
3378                    mUserPaddingRightInitial = rightPadding;
3379                    rightPaddingDefined = true;
3380                    break;
3381                case com.android.internal.R.styleable.View_paddingBottom:
3382                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3383                    break;
3384                case com.android.internal.R.styleable.View_paddingStart:
3385                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3386                    startPaddingDefined = true;
3387                    break;
3388                case com.android.internal.R.styleable.View_paddingEnd:
3389                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3390                    endPaddingDefined = true;
3391                    break;
3392                case com.android.internal.R.styleable.View_scrollX:
3393                    x = a.getDimensionPixelOffset(attr, 0);
3394                    break;
3395                case com.android.internal.R.styleable.View_scrollY:
3396                    y = a.getDimensionPixelOffset(attr, 0);
3397                    break;
3398                case com.android.internal.R.styleable.View_alpha:
3399                    setAlpha(a.getFloat(attr, 1f));
3400                    break;
3401                case com.android.internal.R.styleable.View_transformPivotX:
3402                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3403                    break;
3404                case com.android.internal.R.styleable.View_transformPivotY:
3405                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3406                    break;
3407                case com.android.internal.R.styleable.View_translationX:
3408                    tx = a.getDimensionPixelOffset(attr, 0);
3409                    transformSet = true;
3410                    break;
3411                case com.android.internal.R.styleable.View_translationY:
3412                    ty = a.getDimensionPixelOffset(attr, 0);
3413                    transformSet = true;
3414                    break;
3415                case com.android.internal.R.styleable.View_rotation:
3416                    rotation = a.getFloat(attr, 0);
3417                    transformSet = true;
3418                    break;
3419                case com.android.internal.R.styleable.View_rotationX:
3420                    rotationX = a.getFloat(attr, 0);
3421                    transformSet = true;
3422                    break;
3423                case com.android.internal.R.styleable.View_rotationY:
3424                    rotationY = a.getFloat(attr, 0);
3425                    transformSet = true;
3426                    break;
3427                case com.android.internal.R.styleable.View_scaleX:
3428                    sx = a.getFloat(attr, 1f);
3429                    transformSet = true;
3430                    break;
3431                case com.android.internal.R.styleable.View_scaleY:
3432                    sy = a.getFloat(attr, 1f);
3433                    transformSet = true;
3434                    break;
3435                case com.android.internal.R.styleable.View_id:
3436                    mID = a.getResourceId(attr, NO_ID);
3437                    break;
3438                case com.android.internal.R.styleable.View_tag:
3439                    mTag = a.getText(attr);
3440                    break;
3441                case com.android.internal.R.styleable.View_fitsSystemWindows:
3442                    if (a.getBoolean(attr, false)) {
3443                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3444                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3445                    }
3446                    break;
3447                case com.android.internal.R.styleable.View_focusable:
3448                    if (a.getBoolean(attr, false)) {
3449                        viewFlagValues |= FOCUSABLE;
3450                        viewFlagMasks |= FOCUSABLE_MASK;
3451                    }
3452                    break;
3453                case com.android.internal.R.styleable.View_focusableInTouchMode:
3454                    if (a.getBoolean(attr, false)) {
3455                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3456                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3457                    }
3458                    break;
3459                case com.android.internal.R.styleable.View_clickable:
3460                    if (a.getBoolean(attr, false)) {
3461                        viewFlagValues |= CLICKABLE;
3462                        viewFlagMasks |= CLICKABLE;
3463                    }
3464                    break;
3465                case com.android.internal.R.styleable.View_longClickable:
3466                    if (a.getBoolean(attr, false)) {
3467                        viewFlagValues |= LONG_CLICKABLE;
3468                        viewFlagMasks |= LONG_CLICKABLE;
3469                    }
3470                    break;
3471                case com.android.internal.R.styleable.View_saveEnabled:
3472                    if (!a.getBoolean(attr, true)) {
3473                        viewFlagValues |= SAVE_DISABLED;
3474                        viewFlagMasks |= SAVE_DISABLED_MASK;
3475                    }
3476                    break;
3477                case com.android.internal.R.styleable.View_duplicateParentState:
3478                    if (a.getBoolean(attr, false)) {
3479                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3480                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3481                    }
3482                    break;
3483                case com.android.internal.R.styleable.View_visibility:
3484                    final int visibility = a.getInt(attr, 0);
3485                    if (visibility != 0) {
3486                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3487                        viewFlagMasks |= VISIBILITY_MASK;
3488                    }
3489                    break;
3490                case com.android.internal.R.styleable.View_layoutDirection:
3491                    // Clear any layout direction flags (included resolved bits) already set
3492                    mPrivateFlags2 &=
3493                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3494                    // Set the layout direction flags depending on the value of the attribute
3495                    final int layoutDirection = a.getInt(attr, -1);
3496                    final int value = (layoutDirection != -1) ?
3497                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3498                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3499                    break;
3500                case com.android.internal.R.styleable.View_drawingCacheQuality:
3501                    final int cacheQuality = a.getInt(attr, 0);
3502                    if (cacheQuality != 0) {
3503                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3504                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3505                    }
3506                    break;
3507                case com.android.internal.R.styleable.View_contentDescription:
3508                    setContentDescription(a.getString(attr));
3509                    break;
3510                case com.android.internal.R.styleable.View_labelFor:
3511                    setLabelFor(a.getResourceId(attr, NO_ID));
3512                    break;
3513                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3514                    if (!a.getBoolean(attr, true)) {
3515                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3516                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3517                    }
3518                    break;
3519                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3520                    if (!a.getBoolean(attr, true)) {
3521                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3522                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3523                    }
3524                    break;
3525                case R.styleable.View_scrollbars:
3526                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3527                    if (scrollbars != SCROLLBARS_NONE) {
3528                        viewFlagValues |= scrollbars;
3529                        viewFlagMasks |= SCROLLBARS_MASK;
3530                        initializeScrollbars = true;
3531                    }
3532                    break;
3533                //noinspection deprecation
3534                case R.styleable.View_fadingEdge:
3535                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3536                        // Ignore the attribute starting with ICS
3537                        break;
3538                    }
3539                    // With builds < ICS, fall through and apply fading edges
3540                case R.styleable.View_requiresFadingEdge:
3541                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3542                    if (fadingEdge != FADING_EDGE_NONE) {
3543                        viewFlagValues |= fadingEdge;
3544                        viewFlagMasks |= FADING_EDGE_MASK;
3545                        initializeFadingEdge(a);
3546                    }
3547                    break;
3548                case R.styleable.View_scrollbarStyle:
3549                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3550                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3551                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3552                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3553                    }
3554                    break;
3555                case R.styleable.View_isScrollContainer:
3556                    setScrollContainer = true;
3557                    if (a.getBoolean(attr, false)) {
3558                        setScrollContainer(true);
3559                    }
3560                    break;
3561                case com.android.internal.R.styleable.View_keepScreenOn:
3562                    if (a.getBoolean(attr, false)) {
3563                        viewFlagValues |= KEEP_SCREEN_ON;
3564                        viewFlagMasks |= KEEP_SCREEN_ON;
3565                    }
3566                    break;
3567                case R.styleable.View_filterTouchesWhenObscured:
3568                    if (a.getBoolean(attr, false)) {
3569                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3570                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3571                    }
3572                    break;
3573                case R.styleable.View_nextFocusLeft:
3574                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3575                    break;
3576                case R.styleable.View_nextFocusRight:
3577                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3578                    break;
3579                case R.styleable.View_nextFocusUp:
3580                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3581                    break;
3582                case R.styleable.View_nextFocusDown:
3583                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3584                    break;
3585                case R.styleable.View_nextFocusForward:
3586                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3587                    break;
3588                case R.styleable.View_minWidth:
3589                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3590                    break;
3591                case R.styleable.View_minHeight:
3592                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3593                    break;
3594                case R.styleable.View_onClick:
3595                    if (context.isRestricted()) {
3596                        throw new IllegalStateException("The android:onClick attribute cannot "
3597                                + "be used within a restricted context");
3598                    }
3599
3600                    final String handlerName = a.getString(attr);
3601                    if (handlerName != null) {
3602                        setOnClickListener(new OnClickListener() {
3603                            private Method mHandler;
3604
3605                            public void onClick(View v) {
3606                                if (mHandler == null) {
3607                                    try {
3608                                        mHandler = getContext().getClass().getMethod(handlerName,
3609                                                View.class);
3610                                    } catch (NoSuchMethodException e) {
3611                                        int id = getId();
3612                                        String idText = id == NO_ID ? "" : " with id '"
3613                                                + getContext().getResources().getResourceEntryName(
3614                                                    id) + "'";
3615                                        throw new IllegalStateException("Could not find a method " +
3616                                                handlerName + "(View) in the activity "
3617                                                + getContext().getClass() + " for onClick handler"
3618                                                + " on view " + View.this.getClass() + idText, e);
3619                                    }
3620                                }
3621
3622                                try {
3623                                    mHandler.invoke(getContext(), View.this);
3624                                } catch (IllegalAccessException e) {
3625                                    throw new IllegalStateException("Could not execute non "
3626                                            + "public method of the activity", e);
3627                                } catch (InvocationTargetException e) {
3628                                    throw new IllegalStateException("Could not execute "
3629                                            + "method of the activity", e);
3630                                }
3631                            }
3632                        });
3633                    }
3634                    break;
3635                case R.styleable.View_overScrollMode:
3636                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3637                    break;
3638                case R.styleable.View_verticalScrollbarPosition:
3639                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3640                    break;
3641                case R.styleable.View_layerType:
3642                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3643                    break;
3644                case R.styleable.View_textDirection:
3645                    // Clear any text direction flag already set
3646                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3647                    // Set the text direction flags depending on the value of the attribute
3648                    final int textDirection = a.getInt(attr, -1);
3649                    if (textDirection != -1) {
3650                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3651                    }
3652                    break;
3653                case R.styleable.View_textAlignment:
3654                    // Clear any text alignment flag already set
3655                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3656                    // Set the text alignment flag depending on the value of the attribute
3657                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3658                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3659                    break;
3660                case R.styleable.View_importantForAccessibility:
3661                    setImportantForAccessibility(a.getInt(attr,
3662                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3663                    break;
3664            }
3665        }
3666
3667        setOverScrollMode(overScrollMode);
3668
3669        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3670        // the resolved layout direction). Those cached values will be used later during padding
3671        // resolution.
3672        mUserPaddingStart = startPadding;
3673        mUserPaddingEnd = endPadding;
3674
3675        if (background != null) {
3676            setBackground(background);
3677        }
3678
3679        if (padding >= 0) {
3680            leftPadding = padding;
3681            topPadding = padding;
3682            rightPadding = padding;
3683            bottomPadding = padding;
3684            mUserPaddingLeftInitial = padding;
3685            mUserPaddingRightInitial = padding;
3686        }
3687
3688        if (isRtlCompatibilityMode()) {
3689            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3690            // left / right padding are used if defined (meaning here nothing to do). If they are not
3691            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3692            // start / end and resolve them as left / right (layout direction is not taken into account).
3693            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3694            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3695            // defined.
3696            if (!leftPaddingDefined && startPaddingDefined) {
3697                leftPadding = startPadding;
3698            }
3699            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3700            if (!rightPaddingDefined && endPaddingDefined) {
3701                rightPadding = endPadding;
3702            }
3703            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3704        } else {
3705            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3706            // values defined. Otherwise, left /right values are used.
3707            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3708            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3709            // defined.
3710            if (leftPaddingDefined) {
3711                mUserPaddingLeftInitial = leftPadding;
3712            }
3713            if (rightPaddingDefined) {
3714                mUserPaddingRightInitial = rightPadding;
3715            }
3716        }
3717
3718        internalSetPadding(
3719                mUserPaddingLeftInitial,
3720                topPadding >= 0 ? topPadding : mPaddingTop,
3721                mUserPaddingRightInitial,
3722                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3723
3724        if (viewFlagMasks != 0) {
3725            setFlags(viewFlagValues, viewFlagMasks);
3726        }
3727
3728        if (initializeScrollbars) {
3729            initializeScrollbars(a);
3730        }
3731
3732        a.recycle();
3733
3734        // Needs to be called after mViewFlags is set
3735        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3736            recomputePadding();
3737        }
3738
3739        if (x != 0 || y != 0) {
3740            scrollTo(x, y);
3741        }
3742
3743        if (transformSet) {
3744            setTranslationX(tx);
3745            setTranslationY(ty);
3746            setRotation(rotation);
3747            setRotationX(rotationX);
3748            setRotationY(rotationY);
3749            setScaleX(sx);
3750            setScaleY(sy);
3751        }
3752
3753        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3754            setScrollContainer(true);
3755        }
3756
3757        computeOpaqueFlags();
3758    }
3759
3760    /**
3761     * Non-public constructor for use in testing
3762     */
3763    View() {
3764        mResources = null;
3765    }
3766
3767    public String toString() {
3768        StringBuilder out = new StringBuilder(128);
3769        out.append(getClass().getName());
3770        out.append('{');
3771        out.append(Integer.toHexString(System.identityHashCode(this)));
3772        out.append(' ');
3773        switch (mViewFlags&VISIBILITY_MASK) {
3774            case VISIBLE: out.append('V'); break;
3775            case INVISIBLE: out.append('I'); break;
3776            case GONE: out.append('G'); break;
3777            default: out.append('.'); break;
3778        }
3779        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3780        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3781        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3782        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3783        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3784        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3785        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3786        out.append(' ');
3787        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3788        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3789        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3790        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3791            out.append('p');
3792        } else {
3793            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3794        }
3795        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3796        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3797        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3798        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3799        out.append(' ');
3800        out.append(mLeft);
3801        out.append(',');
3802        out.append(mTop);
3803        out.append('-');
3804        out.append(mRight);
3805        out.append(',');
3806        out.append(mBottom);
3807        final int id = getId();
3808        if (id != NO_ID) {
3809            out.append(" #");
3810            out.append(Integer.toHexString(id));
3811            final Resources r = mResources;
3812            if (id != 0 && r != null) {
3813                try {
3814                    String pkgname;
3815                    switch (id&0xff000000) {
3816                        case 0x7f000000:
3817                            pkgname="app";
3818                            break;
3819                        case 0x01000000:
3820                            pkgname="android";
3821                            break;
3822                        default:
3823                            pkgname = r.getResourcePackageName(id);
3824                            break;
3825                    }
3826                    String typename = r.getResourceTypeName(id);
3827                    String entryname = r.getResourceEntryName(id);
3828                    out.append(" ");
3829                    out.append(pkgname);
3830                    out.append(":");
3831                    out.append(typename);
3832                    out.append("/");
3833                    out.append(entryname);
3834                } catch (Resources.NotFoundException e) {
3835                }
3836            }
3837        }
3838        out.append("}");
3839        return out.toString();
3840    }
3841
3842    /**
3843     * <p>
3844     * Initializes the fading edges from a given set of styled attributes. This
3845     * method should be called by subclasses that need fading edges and when an
3846     * instance of these subclasses is created programmatically rather than
3847     * being inflated from XML. This method is automatically called when the XML
3848     * is inflated.
3849     * </p>
3850     *
3851     * @param a the styled attributes set to initialize the fading edges from
3852     */
3853    protected void initializeFadingEdge(TypedArray a) {
3854        initScrollCache();
3855
3856        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3857                R.styleable.View_fadingEdgeLength,
3858                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3859    }
3860
3861    /**
3862     * Returns the size of the vertical faded edges used to indicate that more
3863     * content in this view is visible.
3864     *
3865     * @return The size in pixels of the vertical faded edge or 0 if vertical
3866     *         faded edges are not enabled for this view.
3867     * @attr ref android.R.styleable#View_fadingEdgeLength
3868     */
3869    public int getVerticalFadingEdgeLength() {
3870        if (isVerticalFadingEdgeEnabled()) {
3871            ScrollabilityCache cache = mScrollCache;
3872            if (cache != null) {
3873                return cache.fadingEdgeLength;
3874            }
3875        }
3876        return 0;
3877    }
3878
3879    /**
3880     * Set the size of the faded edge used to indicate that more content in this
3881     * view is available.  Will not change whether the fading edge is enabled; use
3882     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3883     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3884     * for the vertical or horizontal fading edges.
3885     *
3886     * @param length The size in pixels of the faded edge used to indicate that more
3887     *        content in this view is visible.
3888     */
3889    public void setFadingEdgeLength(int length) {
3890        initScrollCache();
3891        mScrollCache.fadingEdgeLength = length;
3892    }
3893
3894    /**
3895     * Returns the size of the horizontal faded edges used to indicate that more
3896     * content in this view is visible.
3897     *
3898     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3899     *         faded edges are not enabled for this view.
3900     * @attr ref android.R.styleable#View_fadingEdgeLength
3901     */
3902    public int getHorizontalFadingEdgeLength() {
3903        if (isHorizontalFadingEdgeEnabled()) {
3904            ScrollabilityCache cache = mScrollCache;
3905            if (cache != null) {
3906                return cache.fadingEdgeLength;
3907            }
3908        }
3909        return 0;
3910    }
3911
3912    /**
3913     * Returns the width of the vertical scrollbar.
3914     *
3915     * @return The width in pixels of the vertical scrollbar or 0 if there
3916     *         is no vertical scrollbar.
3917     */
3918    public int getVerticalScrollbarWidth() {
3919        ScrollabilityCache cache = mScrollCache;
3920        if (cache != null) {
3921            ScrollBarDrawable scrollBar = cache.scrollBar;
3922            if (scrollBar != null) {
3923                int size = scrollBar.getSize(true);
3924                if (size <= 0) {
3925                    size = cache.scrollBarSize;
3926                }
3927                return size;
3928            }
3929            return 0;
3930        }
3931        return 0;
3932    }
3933
3934    /**
3935     * Returns the height of the horizontal scrollbar.
3936     *
3937     * @return The height in pixels of the horizontal scrollbar or 0 if
3938     *         there is no horizontal scrollbar.
3939     */
3940    protected int getHorizontalScrollbarHeight() {
3941        ScrollabilityCache cache = mScrollCache;
3942        if (cache != null) {
3943            ScrollBarDrawable scrollBar = cache.scrollBar;
3944            if (scrollBar != null) {
3945                int size = scrollBar.getSize(false);
3946                if (size <= 0) {
3947                    size = cache.scrollBarSize;
3948                }
3949                return size;
3950            }
3951            return 0;
3952        }
3953        return 0;
3954    }
3955
3956    /**
3957     * <p>
3958     * Initializes the scrollbars from a given set of styled attributes. This
3959     * method should be called by subclasses that need scrollbars and when an
3960     * instance of these subclasses is created programmatically rather than
3961     * being inflated from XML. This method is automatically called when the XML
3962     * is inflated.
3963     * </p>
3964     *
3965     * @param a the styled attributes set to initialize the scrollbars from
3966     */
3967    protected void initializeScrollbars(TypedArray a) {
3968        initScrollCache();
3969
3970        final ScrollabilityCache scrollabilityCache = mScrollCache;
3971
3972        if (scrollabilityCache.scrollBar == null) {
3973            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3974        }
3975
3976        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3977
3978        if (!fadeScrollbars) {
3979            scrollabilityCache.state = ScrollabilityCache.ON;
3980        }
3981        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3982
3983
3984        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3985                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3986                        .getScrollBarFadeDuration());
3987        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3988                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3989                ViewConfiguration.getScrollDefaultDelay());
3990
3991
3992        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3993                com.android.internal.R.styleable.View_scrollbarSize,
3994                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3995
3996        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3997        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3998
3999        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
4000        if (thumb != null) {
4001            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
4002        }
4003
4004        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
4005                false);
4006        if (alwaysDraw) {
4007            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4008        }
4009
4010        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4011        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4012
4013        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4014        if (thumb != null) {
4015            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4016        }
4017
4018        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4019                false);
4020        if (alwaysDraw) {
4021            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4022        }
4023
4024        // Apply layout direction to the new Drawables if needed
4025        final int layoutDirection = getLayoutDirection();
4026        if (track != null) {
4027            track.setLayoutDirection(layoutDirection);
4028        }
4029        if (thumb != null) {
4030            thumb.setLayoutDirection(layoutDirection);
4031        }
4032
4033        // Re-apply user/background padding so that scrollbar(s) get added
4034        resolvePadding();
4035    }
4036
4037    /**
4038     * <p>
4039     * Initalizes the scrollability cache if necessary.
4040     * </p>
4041     */
4042    private void initScrollCache() {
4043        if (mScrollCache == null) {
4044            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4045        }
4046    }
4047
4048    private ScrollabilityCache getScrollCache() {
4049        initScrollCache();
4050        return mScrollCache;
4051    }
4052
4053    /**
4054     * Set the position of the vertical scroll bar. Should be one of
4055     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4056     * {@link #SCROLLBAR_POSITION_RIGHT}.
4057     *
4058     * @param position Where the vertical scroll bar should be positioned.
4059     */
4060    public void setVerticalScrollbarPosition(int position) {
4061        if (mVerticalScrollbarPosition != position) {
4062            mVerticalScrollbarPosition = position;
4063            computeOpaqueFlags();
4064            resolvePadding();
4065        }
4066    }
4067
4068    /**
4069     * @return The position where the vertical scroll bar will show, if applicable.
4070     * @see #setVerticalScrollbarPosition(int)
4071     */
4072    public int getVerticalScrollbarPosition() {
4073        return mVerticalScrollbarPosition;
4074    }
4075
4076    ListenerInfo getListenerInfo() {
4077        if (mListenerInfo != null) {
4078            return mListenerInfo;
4079        }
4080        mListenerInfo = new ListenerInfo();
4081        return mListenerInfo;
4082    }
4083
4084    /**
4085     * Register a callback to be invoked when focus of this view changed.
4086     *
4087     * @param l The callback that will run.
4088     */
4089    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4090        getListenerInfo().mOnFocusChangeListener = l;
4091    }
4092
4093    /**
4094     * Add a listener that will be called when the bounds of the view change due to
4095     * layout processing.
4096     *
4097     * @param listener The listener that will be called when layout bounds change.
4098     */
4099    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4100        ListenerInfo li = getListenerInfo();
4101        if (li.mOnLayoutChangeListeners == null) {
4102            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4103        }
4104        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4105            li.mOnLayoutChangeListeners.add(listener);
4106        }
4107    }
4108
4109    /**
4110     * Remove a listener for layout changes.
4111     *
4112     * @param listener The listener for layout bounds change.
4113     */
4114    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4115        ListenerInfo li = mListenerInfo;
4116        if (li == null || li.mOnLayoutChangeListeners == null) {
4117            return;
4118        }
4119        li.mOnLayoutChangeListeners.remove(listener);
4120    }
4121
4122    /**
4123     * Add a listener for attach state changes.
4124     *
4125     * This listener will be called whenever this view is attached or detached
4126     * from a window. Remove the listener using
4127     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4128     *
4129     * @param listener Listener to attach
4130     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4131     */
4132    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4133        ListenerInfo li = getListenerInfo();
4134        if (li.mOnAttachStateChangeListeners == null) {
4135            li.mOnAttachStateChangeListeners
4136                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4137        }
4138        li.mOnAttachStateChangeListeners.add(listener);
4139    }
4140
4141    /**
4142     * Remove a listener for attach state changes. The listener will receive no further
4143     * notification of window attach/detach events.
4144     *
4145     * @param listener Listener to remove
4146     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4147     */
4148    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4149        ListenerInfo li = mListenerInfo;
4150        if (li == null || li.mOnAttachStateChangeListeners == null) {
4151            return;
4152        }
4153        li.mOnAttachStateChangeListeners.remove(listener);
4154    }
4155
4156    /**
4157     * Returns the focus-change callback registered for this view.
4158     *
4159     * @return The callback, or null if one is not registered.
4160     */
4161    public OnFocusChangeListener getOnFocusChangeListener() {
4162        ListenerInfo li = mListenerInfo;
4163        return li != null ? li.mOnFocusChangeListener : null;
4164    }
4165
4166    /**
4167     * Register a callback to be invoked when this view is clicked. If this view is not
4168     * clickable, it becomes clickable.
4169     *
4170     * @param l The callback that will run
4171     *
4172     * @see #setClickable(boolean)
4173     */
4174    public void setOnClickListener(OnClickListener l) {
4175        if (!isClickable()) {
4176            setClickable(true);
4177        }
4178        getListenerInfo().mOnClickListener = l;
4179    }
4180
4181    /**
4182     * Return whether this view has an attached OnClickListener.  Returns
4183     * true if there is a listener, false if there is none.
4184     */
4185    public boolean hasOnClickListeners() {
4186        ListenerInfo li = mListenerInfo;
4187        return (li != null && li.mOnClickListener != null);
4188    }
4189
4190    /**
4191     * Register a callback to be invoked when this view is clicked and held. If this view is not
4192     * long clickable, it becomes long clickable.
4193     *
4194     * @param l The callback that will run
4195     *
4196     * @see #setLongClickable(boolean)
4197     */
4198    public void setOnLongClickListener(OnLongClickListener l) {
4199        if (!isLongClickable()) {
4200            setLongClickable(true);
4201        }
4202        getListenerInfo().mOnLongClickListener = l;
4203    }
4204
4205    /**
4206     * Register a callback to be invoked when the context menu for this view is
4207     * being built. If this view is not long clickable, it becomes long clickable.
4208     *
4209     * @param l The callback that will run
4210     *
4211     */
4212    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4213        if (!isLongClickable()) {
4214            setLongClickable(true);
4215        }
4216        getListenerInfo().mOnCreateContextMenuListener = l;
4217    }
4218
4219    /**
4220     * Call this view's OnClickListener, if it is defined.  Performs all normal
4221     * actions associated with clicking: reporting accessibility event, playing
4222     * a sound, etc.
4223     *
4224     * @return True there was an assigned OnClickListener that was called, false
4225     *         otherwise is returned.
4226     */
4227    public boolean performClick() {
4228        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4229
4230        ListenerInfo li = mListenerInfo;
4231        if (li != null && li.mOnClickListener != null) {
4232            playSoundEffect(SoundEffectConstants.CLICK);
4233            li.mOnClickListener.onClick(this);
4234            return true;
4235        }
4236
4237        return false;
4238    }
4239
4240    /**
4241     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4242     * this only calls the listener, and does not do any associated clicking
4243     * actions like reporting an accessibility event.
4244     *
4245     * @return True there was an assigned OnClickListener that was called, false
4246     *         otherwise is returned.
4247     */
4248    public boolean callOnClick() {
4249        ListenerInfo li = mListenerInfo;
4250        if (li != null && li.mOnClickListener != null) {
4251            li.mOnClickListener.onClick(this);
4252            return true;
4253        }
4254        return false;
4255    }
4256
4257    /**
4258     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4259     * OnLongClickListener did not consume the event.
4260     *
4261     * @return True if one of the above receivers consumed the event, false otherwise.
4262     */
4263    public boolean performLongClick() {
4264        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4265
4266        boolean handled = false;
4267        ListenerInfo li = mListenerInfo;
4268        if (li != null && li.mOnLongClickListener != null) {
4269            handled = li.mOnLongClickListener.onLongClick(View.this);
4270        }
4271        if (!handled) {
4272            handled = showContextMenu();
4273        }
4274        if (handled) {
4275            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4276        }
4277        return handled;
4278    }
4279
4280    /**
4281     * Performs button-related actions during a touch down event.
4282     *
4283     * @param event The event.
4284     * @return True if the down was consumed.
4285     *
4286     * @hide
4287     */
4288    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4289        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4290            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4291                return true;
4292            }
4293        }
4294        return false;
4295    }
4296
4297    /**
4298     * Bring up the context menu for this view.
4299     *
4300     * @return Whether a context menu was displayed.
4301     */
4302    public boolean showContextMenu() {
4303        return getParent().showContextMenuForChild(this);
4304    }
4305
4306    /**
4307     * Bring up the context menu for this view, referring to the item under the specified point.
4308     *
4309     * @param x The referenced x coordinate.
4310     * @param y The referenced y coordinate.
4311     * @param metaState The keyboard modifiers that were pressed.
4312     * @return Whether a context menu was displayed.
4313     *
4314     * @hide
4315     */
4316    public boolean showContextMenu(float x, float y, int metaState) {
4317        return showContextMenu();
4318    }
4319
4320    /**
4321     * Start an action mode.
4322     *
4323     * @param callback Callback that will control the lifecycle of the action mode
4324     * @return The new action mode if it is started, null otherwise
4325     *
4326     * @see ActionMode
4327     */
4328    public ActionMode startActionMode(ActionMode.Callback callback) {
4329        ViewParent parent = getParent();
4330        if (parent == null) return null;
4331        return parent.startActionModeForChild(this, callback);
4332    }
4333
4334    /**
4335     * Register a callback to be invoked when a hardware key is pressed in this view.
4336     * Key presses in software input methods will generally not trigger the methods of
4337     * this listener.
4338     * @param l the key listener to attach to this view
4339     */
4340    public void setOnKeyListener(OnKeyListener l) {
4341        getListenerInfo().mOnKeyListener = l;
4342    }
4343
4344    /**
4345     * Register a callback to be invoked when a touch event is sent to this view.
4346     * @param l the touch listener to attach to this view
4347     */
4348    public void setOnTouchListener(OnTouchListener l) {
4349        getListenerInfo().mOnTouchListener = l;
4350    }
4351
4352    /**
4353     * Register a callback to be invoked when a generic motion event is sent to this view.
4354     * @param l the generic motion listener to attach to this view
4355     */
4356    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4357        getListenerInfo().mOnGenericMotionListener = l;
4358    }
4359
4360    /**
4361     * Register a callback to be invoked when a hover event is sent to this view.
4362     * @param l the hover listener to attach to this view
4363     */
4364    public void setOnHoverListener(OnHoverListener l) {
4365        getListenerInfo().mOnHoverListener = l;
4366    }
4367
4368    /**
4369     * Register a drag event listener callback object for this View. The parameter is
4370     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4371     * View, the system calls the
4372     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4373     * @param l An implementation of {@link android.view.View.OnDragListener}.
4374     */
4375    public void setOnDragListener(OnDragListener l) {
4376        getListenerInfo().mOnDragListener = l;
4377    }
4378
4379    /**
4380     * Give this view focus. This will cause
4381     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4382     *
4383     * Note: this does not check whether this {@link View} should get focus, it just
4384     * gives it focus no matter what.  It should only be called internally by framework
4385     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4386     *
4387     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4388     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4389     *        focus moved when requestFocus() is called. It may not always
4390     *        apply, in which case use the default View.FOCUS_DOWN.
4391     * @param previouslyFocusedRect The rectangle of the view that had focus
4392     *        prior in this View's coordinate system.
4393     */
4394    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4395        if (DBG) {
4396            System.out.println(this + " requestFocus()");
4397        }
4398
4399        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4400            mPrivateFlags |= PFLAG_FOCUSED;
4401
4402            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4403
4404            if (mParent != null) {
4405                mParent.requestChildFocus(this, this);
4406            }
4407
4408            if (mAttachInfo != null) {
4409                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4410            }
4411
4412            onFocusChanged(true, direction, previouslyFocusedRect);
4413            refreshDrawableState();
4414
4415            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4416                notifyAccessibilityStateChanged();
4417            }
4418        }
4419    }
4420
4421    /**
4422     * Request that a rectangle of this view be visible on the screen,
4423     * scrolling if necessary just enough.
4424     *
4425     * <p>A View should call this if it maintains some notion of which part
4426     * of its content is interesting.  For example, a text editing view
4427     * should call this when its cursor moves.
4428     *
4429     * @param rectangle The rectangle.
4430     * @return Whether any parent scrolled.
4431     */
4432    public boolean requestRectangleOnScreen(Rect rectangle) {
4433        return requestRectangleOnScreen(rectangle, false);
4434    }
4435
4436    /**
4437     * Request that a rectangle of this view be visible on the screen,
4438     * scrolling if necessary just enough.
4439     *
4440     * <p>A View should call this if it maintains some notion of which part
4441     * of its content is interesting.  For example, a text editing view
4442     * should call this when its cursor moves.
4443     *
4444     * <p>When <code>immediate</code> is set to true, scrolling will not be
4445     * animated.
4446     *
4447     * @param rectangle The rectangle.
4448     * @param immediate True to forbid animated scrolling, false otherwise
4449     * @return Whether any parent scrolled.
4450     */
4451    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4452        if (mParent == null) {
4453            return false;
4454        }
4455
4456        View child = this;
4457
4458        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4459        position.set(rectangle);
4460
4461        ViewParent parent = mParent;
4462        boolean scrolled = false;
4463        while (parent != null) {
4464            rectangle.set((int) position.left, (int) position.top,
4465                    (int) position.right, (int) position.bottom);
4466
4467            scrolled |= parent.requestChildRectangleOnScreen(child,
4468                    rectangle, immediate);
4469
4470            if (!child.hasIdentityMatrix()) {
4471                child.getMatrix().mapRect(position);
4472            }
4473
4474            position.offset(child.mLeft, child.mTop);
4475
4476            if (!(parent instanceof View)) {
4477                break;
4478            }
4479
4480            View parentView = (View) parent;
4481
4482            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4483
4484            child = parentView;
4485            parent = child.getParent();
4486        }
4487
4488        return scrolled;
4489    }
4490
4491    /**
4492     * Called when this view wants to give up focus. If focus is cleared
4493     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4494     * <p>
4495     * <strong>Note:</strong> When a View clears focus the framework is trying
4496     * to give focus to the first focusable View from the top. Hence, if this
4497     * View is the first from the top that can take focus, then all callbacks
4498     * related to clearing focus will be invoked after wich the framework will
4499     * give focus to this view.
4500     * </p>
4501     */
4502    public void clearFocus() {
4503        if (DBG) {
4504            System.out.println(this + " clearFocus()");
4505        }
4506
4507        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4508            mPrivateFlags &= ~PFLAG_FOCUSED;
4509
4510            if (mParent != null) {
4511                mParent.clearChildFocus(this);
4512            }
4513
4514            onFocusChanged(false, 0, null);
4515
4516            refreshDrawableState();
4517
4518            if (!rootViewRequestFocus()) {
4519                notifyGlobalFocusCleared(this);
4520            }
4521
4522            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4523                notifyAccessibilityStateChanged();
4524            }
4525        }
4526    }
4527
4528    void notifyGlobalFocusCleared(View oldFocus) {
4529        if (oldFocus != null && mAttachInfo != null) {
4530            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4531        }
4532    }
4533
4534    boolean rootViewRequestFocus() {
4535        View root = getRootView();
4536        if (root != null) {
4537            return root.requestFocus();
4538        }
4539        return false;
4540    }
4541
4542    /**
4543     * Called internally by the view system when a new view is getting focus.
4544     * This is what clears the old focus.
4545     */
4546    void unFocus() {
4547        if (DBG) {
4548            System.out.println(this + " unFocus()");
4549        }
4550
4551        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4552            mPrivateFlags &= ~PFLAG_FOCUSED;
4553
4554            onFocusChanged(false, 0, null);
4555            refreshDrawableState();
4556
4557            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4558                notifyAccessibilityStateChanged();
4559            }
4560        }
4561    }
4562
4563    /**
4564     * Returns true if this view has focus iteself, or is the ancestor of the
4565     * view that has focus.
4566     *
4567     * @return True if this view has or contains focus, false otherwise.
4568     */
4569    @ViewDebug.ExportedProperty(category = "focus")
4570    public boolean hasFocus() {
4571        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4572    }
4573
4574    /**
4575     * Returns true if this view is focusable or if it contains a reachable View
4576     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4577     * is a View whose parents do not block descendants focus.
4578     *
4579     * Only {@link #VISIBLE} views are considered focusable.
4580     *
4581     * @return True if the view is focusable or if the view contains a focusable
4582     *         View, false otherwise.
4583     *
4584     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4585     */
4586    public boolean hasFocusable() {
4587        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4588    }
4589
4590    /**
4591     * Called by the view system when the focus state of this view changes.
4592     * When the focus change event is caused by directional navigation, direction
4593     * and previouslyFocusedRect provide insight into where the focus is coming from.
4594     * When overriding, be sure to call up through to the super class so that
4595     * the standard focus handling will occur.
4596     *
4597     * @param gainFocus True if the View has focus; false otherwise.
4598     * @param direction The direction focus has moved when requestFocus()
4599     *                  is called to give this view focus. Values are
4600     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4601     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4602     *                  It may not always apply, in which case use the default.
4603     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4604     *        system, of the previously focused view.  If applicable, this will be
4605     *        passed in as finer grained information about where the focus is coming
4606     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4607     */
4608    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4609        if (gainFocus) {
4610            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4611                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4612            }
4613        }
4614
4615        InputMethodManager imm = InputMethodManager.peekInstance();
4616        if (!gainFocus) {
4617            if (isPressed()) {
4618                setPressed(false);
4619            }
4620            if (imm != null && mAttachInfo != null
4621                    && mAttachInfo.mHasWindowFocus) {
4622                imm.focusOut(this);
4623            }
4624            onFocusLost();
4625        } else if (imm != null && mAttachInfo != null
4626                && mAttachInfo.mHasWindowFocus) {
4627            imm.focusIn(this);
4628        }
4629
4630        invalidate(true);
4631        ListenerInfo li = mListenerInfo;
4632        if (li != null && li.mOnFocusChangeListener != null) {
4633            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4634        }
4635
4636        if (mAttachInfo != null) {
4637            mAttachInfo.mKeyDispatchState.reset(this);
4638        }
4639    }
4640
4641    /**
4642     * Sends an accessibility event of the given type. If accessibility is
4643     * not enabled this method has no effect. The default implementation calls
4644     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4645     * to populate information about the event source (this View), then calls
4646     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4647     * populate the text content of the event source including its descendants,
4648     * and last calls
4649     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4650     * on its parent to resuest sending of the event to interested parties.
4651     * <p>
4652     * If an {@link AccessibilityDelegate} has been specified via calling
4653     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4654     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4655     * responsible for handling this call.
4656     * </p>
4657     *
4658     * @param eventType The type of the event to send, as defined by several types from
4659     * {@link android.view.accessibility.AccessibilityEvent}, such as
4660     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4661     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4662     *
4663     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4664     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4665     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4666     * @see AccessibilityDelegate
4667     */
4668    public void sendAccessibilityEvent(int eventType) {
4669        if (mAccessibilityDelegate != null) {
4670            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4671        } else {
4672            sendAccessibilityEventInternal(eventType);
4673        }
4674    }
4675
4676    /**
4677     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4678     * {@link AccessibilityEvent} to make an announcement which is related to some
4679     * sort of a context change for which none of the events representing UI transitions
4680     * is a good fit. For example, announcing a new page in a book. If accessibility
4681     * is not enabled this method does nothing.
4682     *
4683     * @param text The announcement text.
4684     */
4685    public void announceForAccessibility(CharSequence text) {
4686        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4687            AccessibilityEvent event = AccessibilityEvent.obtain(
4688                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4689            onInitializeAccessibilityEvent(event);
4690            event.getText().add(text);
4691            event.setContentDescription(null);
4692            mParent.requestSendAccessibilityEvent(this, event);
4693        }
4694    }
4695
4696    /**
4697     * @see #sendAccessibilityEvent(int)
4698     *
4699     * Note: Called from the default {@link AccessibilityDelegate}.
4700     */
4701    void sendAccessibilityEventInternal(int eventType) {
4702        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4703            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4704        }
4705    }
4706
4707    /**
4708     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4709     * takes as an argument an empty {@link AccessibilityEvent} and does not
4710     * perform a check whether accessibility is enabled.
4711     * <p>
4712     * If an {@link AccessibilityDelegate} has been specified via calling
4713     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4714     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4715     * is responsible for handling this call.
4716     * </p>
4717     *
4718     * @param event The event to send.
4719     *
4720     * @see #sendAccessibilityEvent(int)
4721     */
4722    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4723        if (mAccessibilityDelegate != null) {
4724            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4725        } else {
4726            sendAccessibilityEventUncheckedInternal(event);
4727        }
4728    }
4729
4730    /**
4731     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4732     *
4733     * Note: Called from the default {@link AccessibilityDelegate}.
4734     */
4735    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4736        if (!isShown()) {
4737            return;
4738        }
4739        onInitializeAccessibilityEvent(event);
4740        // Only a subset of accessibility events populates text content.
4741        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4742            dispatchPopulateAccessibilityEvent(event);
4743        }
4744        // In the beginning we called #isShown(), so we know that getParent() is not null.
4745        getParent().requestSendAccessibilityEvent(this, event);
4746    }
4747
4748    /**
4749     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4750     * to its children for adding their text content to the event. Note that the
4751     * event text is populated in a separate dispatch path since we add to the
4752     * event not only the text of the source but also the text of all its descendants.
4753     * A typical implementation will call
4754     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4755     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4756     * on each child. Override this method if custom population of the event text
4757     * content is required.
4758     * <p>
4759     * If an {@link AccessibilityDelegate} has been specified via calling
4760     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4761     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4762     * is responsible for handling this call.
4763     * </p>
4764     * <p>
4765     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4766     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4767     * </p>
4768     *
4769     * @param event The event.
4770     *
4771     * @return True if the event population was completed.
4772     */
4773    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4774        if (mAccessibilityDelegate != null) {
4775            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4776        } else {
4777            return dispatchPopulateAccessibilityEventInternal(event);
4778        }
4779    }
4780
4781    /**
4782     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4783     *
4784     * Note: Called from the default {@link AccessibilityDelegate}.
4785     */
4786    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4787        onPopulateAccessibilityEvent(event);
4788        return false;
4789    }
4790
4791    /**
4792     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4793     * giving a chance to this View to populate the accessibility event with its
4794     * text content. While this method is free to modify event
4795     * attributes other than text content, doing so should normally be performed in
4796     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4797     * <p>
4798     * Example: Adding formatted date string to an accessibility event in addition
4799     *          to the text added by the super implementation:
4800     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4801     *     super.onPopulateAccessibilityEvent(event);
4802     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4803     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4804     *         mCurrentDate.getTimeInMillis(), flags);
4805     *     event.getText().add(selectedDateUtterance);
4806     * }</pre>
4807     * <p>
4808     * If an {@link AccessibilityDelegate} has been specified via calling
4809     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4810     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4811     * is responsible for handling this call.
4812     * </p>
4813     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4814     * information to the event, in case the default implementation has basic information to add.
4815     * </p>
4816     *
4817     * @param event The accessibility event which to populate.
4818     *
4819     * @see #sendAccessibilityEvent(int)
4820     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4821     */
4822    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4823        if (mAccessibilityDelegate != null) {
4824            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4825        } else {
4826            onPopulateAccessibilityEventInternal(event);
4827        }
4828    }
4829
4830    /**
4831     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4832     *
4833     * Note: Called from the default {@link AccessibilityDelegate}.
4834     */
4835    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4836
4837    }
4838
4839    /**
4840     * Initializes an {@link AccessibilityEvent} with information about
4841     * this View which is the event source. In other words, the source of
4842     * an accessibility event is the view whose state change triggered firing
4843     * the event.
4844     * <p>
4845     * Example: Setting the password property of an event in addition
4846     *          to properties set by the super implementation:
4847     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4848     *     super.onInitializeAccessibilityEvent(event);
4849     *     event.setPassword(true);
4850     * }</pre>
4851     * <p>
4852     * If an {@link AccessibilityDelegate} has been specified via calling
4853     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4854     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4855     * is responsible for handling this call.
4856     * </p>
4857     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4858     * information to the event, in case the default implementation has basic information to add.
4859     * </p>
4860     * @param event The event to initialize.
4861     *
4862     * @see #sendAccessibilityEvent(int)
4863     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4864     */
4865    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4866        if (mAccessibilityDelegate != null) {
4867            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4868        } else {
4869            onInitializeAccessibilityEventInternal(event);
4870        }
4871    }
4872
4873    /**
4874     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4875     *
4876     * Note: Called from the default {@link AccessibilityDelegate}.
4877     */
4878    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4879        event.setSource(this);
4880        event.setClassName(View.class.getName());
4881        event.setPackageName(getContext().getPackageName());
4882        event.setEnabled(isEnabled());
4883        event.setContentDescription(mContentDescription);
4884
4885        switch (event.getEventType()) {
4886            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4887                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4888                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4889                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4890                event.setItemCount(focusablesTempList.size());
4891                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4892                if (mAttachInfo != null) {
4893                    focusablesTempList.clear();
4894                }
4895            } break;
4896            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4897                CharSequence text = getIterableTextForAccessibility();
4898                if (text != null && text.length() > 0) {
4899                    event.setFromIndex(getAccessibilitySelectionStart());
4900                    event.setToIndex(getAccessibilitySelectionEnd());
4901                    event.setItemCount(text.length());
4902                }
4903            } break;
4904        }
4905    }
4906
4907    /**
4908     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4909     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4910     * This method is responsible for obtaining an accessibility node info from a
4911     * pool of reusable instances and calling
4912     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4913     * initialize the former.
4914     * <p>
4915     * Note: The client is responsible for recycling the obtained instance by calling
4916     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4917     * </p>
4918     *
4919     * @return A populated {@link AccessibilityNodeInfo}.
4920     *
4921     * @see AccessibilityNodeInfo
4922     */
4923    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4924        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4925        if (provider != null) {
4926            return provider.createAccessibilityNodeInfo(View.NO_ID);
4927        } else {
4928            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4929            onInitializeAccessibilityNodeInfo(info);
4930            return info;
4931        }
4932    }
4933
4934    /**
4935     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4936     * The base implementation sets:
4937     * <ul>
4938     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4939     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4940     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4941     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4942     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4943     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4944     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4945     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4946     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4947     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4948     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4949     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4950     * </ul>
4951     * <p>
4952     * Subclasses should override this method, call the super implementation,
4953     * and set additional attributes.
4954     * </p>
4955     * <p>
4956     * If an {@link AccessibilityDelegate} has been specified via calling
4957     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4958     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4959     * is responsible for handling this call.
4960     * </p>
4961     *
4962     * @param info The instance to initialize.
4963     */
4964    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4965        if (mAccessibilityDelegate != null) {
4966            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4967        } else {
4968            onInitializeAccessibilityNodeInfoInternal(info);
4969        }
4970    }
4971
4972    /**
4973     * Gets the location of this view in screen coordintates.
4974     *
4975     * @param outRect The output location
4976     */
4977    void getBoundsOnScreen(Rect outRect) {
4978        if (mAttachInfo == null) {
4979            return;
4980        }
4981
4982        RectF position = mAttachInfo.mTmpTransformRect;
4983        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4984
4985        if (!hasIdentityMatrix()) {
4986            getMatrix().mapRect(position);
4987        }
4988
4989        position.offset(mLeft, mTop);
4990
4991        ViewParent parent = mParent;
4992        while (parent instanceof View) {
4993            View parentView = (View) parent;
4994
4995            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4996
4997            if (!parentView.hasIdentityMatrix()) {
4998                parentView.getMatrix().mapRect(position);
4999            }
5000
5001            position.offset(parentView.mLeft, parentView.mTop);
5002
5003            parent = parentView.mParent;
5004        }
5005
5006        if (parent instanceof ViewRootImpl) {
5007            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5008            position.offset(0, -viewRootImpl.mCurScrollY);
5009        }
5010
5011        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5012
5013        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5014                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5015    }
5016
5017    /**
5018     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5019     *
5020     * Note: Called from the default {@link AccessibilityDelegate}.
5021     */
5022    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5023        Rect bounds = mAttachInfo.mTmpInvalRect;
5024
5025        getDrawingRect(bounds);
5026        info.setBoundsInParent(bounds);
5027
5028        getBoundsOnScreen(bounds);
5029        info.setBoundsInScreen(bounds);
5030
5031        ViewParent parent = getParentForAccessibility();
5032        if (parent instanceof View) {
5033            info.setParent((View) parent);
5034        }
5035
5036        if (mID != View.NO_ID) {
5037            View rootView = getRootView();
5038            if (rootView == null) {
5039                rootView = this;
5040            }
5041            View label = rootView.findLabelForView(this, mID);
5042            if (label != null) {
5043                info.setLabeledBy(label);
5044            }
5045
5046            if ((mAttachInfo.mAccessibilityFetchFlags
5047                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0
5048                    && Resources.resourceHasPackage(mID)) {
5049                try {
5050                    String viewId = getResources().getResourceName(mID);
5051                    info.setViewIdResourceName(viewId);
5052                } catch (Resources.NotFoundException nfe) {
5053                    /* ignore */
5054                }
5055            }
5056        }
5057
5058        if (mLabelForId != View.NO_ID) {
5059            View rootView = getRootView();
5060            if (rootView == null) {
5061                rootView = this;
5062            }
5063            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5064            if (labeled != null) {
5065                info.setLabelFor(labeled);
5066            }
5067        }
5068
5069        info.setVisibleToUser(isVisibleToUser());
5070
5071        info.setPackageName(mContext.getPackageName());
5072        info.setClassName(View.class.getName());
5073        info.setContentDescription(getContentDescription());
5074
5075        info.setEnabled(isEnabled());
5076        info.setClickable(isClickable());
5077        info.setFocusable(isFocusable());
5078        info.setFocused(isFocused());
5079        info.setAccessibilityFocused(isAccessibilityFocused());
5080        info.setSelected(isSelected());
5081        info.setLongClickable(isLongClickable());
5082
5083        // TODO: These make sense only if we are in an AdapterView but all
5084        // views can be selected. Maybe from accessibility perspective
5085        // we should report as selectable view in an AdapterView.
5086        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5087        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5088
5089        if (isFocusable()) {
5090            if (isFocused()) {
5091                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5092            } else {
5093                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5094            }
5095        }
5096
5097        if (!isAccessibilityFocused()) {
5098            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5099        } else {
5100            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5101        }
5102
5103        if (isClickable() && isEnabled()) {
5104            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5105        }
5106
5107        if (isLongClickable() && isEnabled()) {
5108            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5109        }
5110
5111        CharSequence text = getIterableTextForAccessibility();
5112        if (text != null && text.length() > 0) {
5113            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5114
5115            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5116            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5117            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5118            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5119                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5120                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5121        }
5122    }
5123
5124    private View findLabelForView(View view, int labeledId) {
5125        if (mMatchLabelForPredicate == null) {
5126            mMatchLabelForPredicate = new MatchLabelForPredicate();
5127        }
5128        mMatchLabelForPredicate.mLabeledId = labeledId;
5129        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5130    }
5131
5132    /**
5133     * Computes whether this view is visible to the user. Such a view is
5134     * attached, visible, all its predecessors are visible, it is not clipped
5135     * entirely by its predecessors, and has an alpha greater than zero.
5136     *
5137     * @return Whether the view is visible on the screen.
5138     *
5139     * @hide
5140     */
5141    protected boolean isVisibleToUser() {
5142        return isVisibleToUser(null);
5143    }
5144
5145    /**
5146     * Computes whether the given portion of this view is visible to the user.
5147     * Such a view is attached, visible, all its predecessors are visible,
5148     * has an alpha greater than zero, and the specified portion is not
5149     * clipped entirely by its predecessors.
5150     *
5151     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5152     *                    <code>null</code>, and the entire view will be tested in this case.
5153     *                    When <code>true</code> is returned by the function, the actual visible
5154     *                    region will be stored in this parameter; that is, if boundInView is fully
5155     *                    contained within the view, no modification will be made, otherwise regions
5156     *                    outside of the visible area of the view will be clipped.
5157     *
5158     * @return Whether the specified portion of the view is visible on the screen.
5159     *
5160     * @hide
5161     */
5162    protected boolean isVisibleToUser(Rect boundInView) {
5163        if (mAttachInfo != null) {
5164            // Attached to invisible window means this view is not visible.
5165            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5166                return false;
5167            }
5168            // An invisible predecessor or one with alpha zero means
5169            // that this view is not visible to the user.
5170            Object current = this;
5171            while (current instanceof View) {
5172                View view = (View) current;
5173                // We have attach info so this view is attached and there is no
5174                // need to check whether we reach to ViewRootImpl on the way up.
5175                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5176                    return false;
5177                }
5178                current = view.mParent;
5179            }
5180            // Check if the view is entirely covered by its predecessors.
5181            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5182            Point offset = mAttachInfo.mPoint;
5183            if (!getGlobalVisibleRect(visibleRect, offset)) {
5184                return false;
5185            }
5186            // Check if the visible portion intersects the rectangle of interest.
5187            if (boundInView != null) {
5188                visibleRect.offset(-offset.x, -offset.y);
5189                return boundInView.intersect(visibleRect);
5190            }
5191            return true;
5192        }
5193        return false;
5194    }
5195
5196    /**
5197     * Returns the delegate for implementing accessibility support via
5198     * composition. For more details see {@link AccessibilityDelegate}.
5199     *
5200     * @return The delegate, or null if none set.
5201     *
5202     * @hide
5203     */
5204    public AccessibilityDelegate getAccessibilityDelegate() {
5205        return mAccessibilityDelegate;
5206    }
5207
5208    /**
5209     * Sets a delegate for implementing accessibility support via composition as
5210     * opposed to inheritance. The delegate's primary use is for implementing
5211     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5212     *
5213     * @param delegate The delegate instance.
5214     *
5215     * @see AccessibilityDelegate
5216     */
5217    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5218        mAccessibilityDelegate = delegate;
5219    }
5220
5221    /**
5222     * Gets the provider for managing a virtual view hierarchy rooted at this View
5223     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5224     * that explore the window content.
5225     * <p>
5226     * If this method returns an instance, this instance is responsible for managing
5227     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5228     * View including the one representing the View itself. Similarly the returned
5229     * instance is responsible for performing accessibility actions on any virtual
5230     * view or the root view itself.
5231     * </p>
5232     * <p>
5233     * If an {@link AccessibilityDelegate} has been specified via calling
5234     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5235     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5236     * is responsible for handling this call.
5237     * </p>
5238     *
5239     * @return The provider.
5240     *
5241     * @see AccessibilityNodeProvider
5242     */
5243    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5244        if (mAccessibilityDelegate != null) {
5245            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5246        } else {
5247            return null;
5248        }
5249    }
5250
5251    /**
5252     * Gets the unique identifier of this view on the screen for accessibility purposes.
5253     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5254     *
5255     * @return The view accessibility id.
5256     *
5257     * @hide
5258     */
5259    public int getAccessibilityViewId() {
5260        if (mAccessibilityViewId == NO_ID) {
5261            mAccessibilityViewId = sNextAccessibilityViewId++;
5262        }
5263        return mAccessibilityViewId;
5264    }
5265
5266    /**
5267     * Gets the unique identifier of the window in which this View reseides.
5268     *
5269     * @return The window accessibility id.
5270     *
5271     * @hide
5272     */
5273    public int getAccessibilityWindowId() {
5274        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5275    }
5276
5277    /**
5278     * Gets the {@link View} description. It briefly describes the view and is
5279     * primarily used for accessibility support. Set this property to enable
5280     * better accessibility support for your application. This is especially
5281     * true for views that do not have textual representation (For example,
5282     * ImageButton).
5283     *
5284     * @return The content description.
5285     *
5286     * @attr ref android.R.styleable#View_contentDescription
5287     */
5288    @ViewDebug.ExportedProperty(category = "accessibility")
5289    public CharSequence getContentDescription() {
5290        return mContentDescription;
5291    }
5292
5293    /**
5294     * Sets the {@link View} description. It briefly describes the view and is
5295     * primarily used for accessibility support. Set this property to enable
5296     * better accessibility support for your application. This is especially
5297     * true for views that do not have textual representation (For example,
5298     * ImageButton).
5299     *
5300     * @param contentDescription The content description.
5301     *
5302     * @attr ref android.R.styleable#View_contentDescription
5303     */
5304    @RemotableViewMethod
5305    public void setContentDescription(CharSequence contentDescription) {
5306        if (mContentDescription == null) {
5307            if (contentDescription == null) {
5308                return;
5309            }
5310        } else if (mContentDescription.equals(contentDescription)) {
5311            return;
5312        }
5313        mContentDescription = contentDescription;
5314        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5315        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5316             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5317        }
5318        notifyAccessibilityStateChanged();
5319    }
5320
5321    /**
5322     * Gets the id of a view for which this view serves as a label for
5323     * accessibility purposes.
5324     *
5325     * @return The labeled view id.
5326     */
5327    @ViewDebug.ExportedProperty(category = "accessibility")
5328    public int getLabelFor() {
5329        return mLabelForId;
5330    }
5331
5332    /**
5333     * Sets the id of a view for which this view serves as a label for
5334     * accessibility purposes.
5335     *
5336     * @param id The labeled view id.
5337     */
5338    @RemotableViewMethod
5339    public void setLabelFor(int id) {
5340        mLabelForId = id;
5341        if (mLabelForId != View.NO_ID
5342                && mID == View.NO_ID) {
5343            mID = generateViewId();
5344        }
5345    }
5346
5347    /**
5348     * Invoked whenever this view loses focus, either by losing window focus or by losing
5349     * focus within its window. This method can be used to clear any state tied to the
5350     * focus. For instance, if a button is held pressed with the trackball and the window
5351     * loses focus, this method can be used to cancel the press.
5352     *
5353     * Subclasses of View overriding this method should always call super.onFocusLost().
5354     *
5355     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5356     * @see #onWindowFocusChanged(boolean)
5357     *
5358     * @hide pending API council approval
5359     */
5360    protected void onFocusLost() {
5361        resetPressedState();
5362    }
5363
5364    private void resetPressedState() {
5365        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5366            return;
5367        }
5368
5369        if (isPressed()) {
5370            setPressed(false);
5371
5372            if (!mHasPerformedLongPress) {
5373                removeLongPressCallback();
5374            }
5375        }
5376    }
5377
5378    /**
5379     * Returns true if this view has focus
5380     *
5381     * @return True if this view has focus, false otherwise.
5382     */
5383    @ViewDebug.ExportedProperty(category = "focus")
5384    public boolean isFocused() {
5385        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5386    }
5387
5388    /**
5389     * Find the view in the hierarchy rooted at this view that currently has
5390     * focus.
5391     *
5392     * @return The view that currently has focus, or null if no focused view can
5393     *         be found.
5394     */
5395    public View findFocus() {
5396        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5397    }
5398
5399    /**
5400     * Indicates whether this view is one of the set of scrollable containers in
5401     * its window.
5402     *
5403     * @return whether this view is one of the set of scrollable containers in
5404     * its window
5405     *
5406     * @attr ref android.R.styleable#View_isScrollContainer
5407     */
5408    public boolean isScrollContainer() {
5409        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5410    }
5411
5412    /**
5413     * Change whether this view is one of the set of scrollable containers in
5414     * its window.  This will be used to determine whether the window can
5415     * resize or must pan when a soft input area is open -- scrollable
5416     * containers allow the window to use resize mode since the container
5417     * will appropriately shrink.
5418     *
5419     * @attr ref android.R.styleable#View_isScrollContainer
5420     */
5421    public void setScrollContainer(boolean isScrollContainer) {
5422        if (isScrollContainer) {
5423            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5424                mAttachInfo.mScrollContainers.add(this);
5425                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5426            }
5427            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5428        } else {
5429            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5430                mAttachInfo.mScrollContainers.remove(this);
5431            }
5432            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5433        }
5434    }
5435
5436    /**
5437     * Returns the quality of the drawing cache.
5438     *
5439     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5440     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5441     *
5442     * @see #setDrawingCacheQuality(int)
5443     * @see #setDrawingCacheEnabled(boolean)
5444     * @see #isDrawingCacheEnabled()
5445     *
5446     * @attr ref android.R.styleable#View_drawingCacheQuality
5447     */
5448    public int getDrawingCacheQuality() {
5449        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5450    }
5451
5452    /**
5453     * Set the drawing cache quality of this view. This value is used only when the
5454     * drawing cache is enabled
5455     *
5456     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5457     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5458     *
5459     * @see #getDrawingCacheQuality()
5460     * @see #setDrawingCacheEnabled(boolean)
5461     * @see #isDrawingCacheEnabled()
5462     *
5463     * @attr ref android.R.styleable#View_drawingCacheQuality
5464     */
5465    public void setDrawingCacheQuality(int quality) {
5466        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5467    }
5468
5469    /**
5470     * Returns whether the screen should remain on, corresponding to the current
5471     * value of {@link #KEEP_SCREEN_ON}.
5472     *
5473     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5474     *
5475     * @see #setKeepScreenOn(boolean)
5476     *
5477     * @attr ref android.R.styleable#View_keepScreenOn
5478     */
5479    public boolean getKeepScreenOn() {
5480        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5481    }
5482
5483    /**
5484     * Controls whether the screen should remain on, modifying the
5485     * value of {@link #KEEP_SCREEN_ON}.
5486     *
5487     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5488     *
5489     * @see #getKeepScreenOn()
5490     *
5491     * @attr ref android.R.styleable#View_keepScreenOn
5492     */
5493    public void setKeepScreenOn(boolean keepScreenOn) {
5494        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5495    }
5496
5497    /**
5498     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5499     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5500     *
5501     * @attr ref android.R.styleable#View_nextFocusLeft
5502     */
5503    public int getNextFocusLeftId() {
5504        return mNextFocusLeftId;
5505    }
5506
5507    /**
5508     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5509     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5510     * decide automatically.
5511     *
5512     * @attr ref android.R.styleable#View_nextFocusLeft
5513     */
5514    public void setNextFocusLeftId(int nextFocusLeftId) {
5515        mNextFocusLeftId = nextFocusLeftId;
5516    }
5517
5518    /**
5519     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5520     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5521     *
5522     * @attr ref android.R.styleable#View_nextFocusRight
5523     */
5524    public int getNextFocusRightId() {
5525        return mNextFocusRightId;
5526    }
5527
5528    /**
5529     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5530     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5531     * decide automatically.
5532     *
5533     * @attr ref android.R.styleable#View_nextFocusRight
5534     */
5535    public void setNextFocusRightId(int nextFocusRightId) {
5536        mNextFocusRightId = nextFocusRightId;
5537    }
5538
5539    /**
5540     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5541     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5542     *
5543     * @attr ref android.R.styleable#View_nextFocusUp
5544     */
5545    public int getNextFocusUpId() {
5546        return mNextFocusUpId;
5547    }
5548
5549    /**
5550     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5551     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5552     * decide automatically.
5553     *
5554     * @attr ref android.R.styleable#View_nextFocusUp
5555     */
5556    public void setNextFocusUpId(int nextFocusUpId) {
5557        mNextFocusUpId = nextFocusUpId;
5558    }
5559
5560    /**
5561     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5562     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5563     *
5564     * @attr ref android.R.styleable#View_nextFocusDown
5565     */
5566    public int getNextFocusDownId() {
5567        return mNextFocusDownId;
5568    }
5569
5570    /**
5571     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5572     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5573     * decide automatically.
5574     *
5575     * @attr ref android.R.styleable#View_nextFocusDown
5576     */
5577    public void setNextFocusDownId(int nextFocusDownId) {
5578        mNextFocusDownId = nextFocusDownId;
5579    }
5580
5581    /**
5582     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5583     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5584     *
5585     * @attr ref android.R.styleable#View_nextFocusForward
5586     */
5587    public int getNextFocusForwardId() {
5588        return mNextFocusForwardId;
5589    }
5590
5591    /**
5592     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5593     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5594     * decide automatically.
5595     *
5596     * @attr ref android.R.styleable#View_nextFocusForward
5597     */
5598    public void setNextFocusForwardId(int nextFocusForwardId) {
5599        mNextFocusForwardId = nextFocusForwardId;
5600    }
5601
5602    /**
5603     * Returns the visibility of this view and all of its ancestors
5604     *
5605     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5606     */
5607    public boolean isShown() {
5608        View current = this;
5609        //noinspection ConstantConditions
5610        do {
5611            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5612                return false;
5613            }
5614            ViewParent parent = current.mParent;
5615            if (parent == null) {
5616                return false; // We are not attached to the view root
5617            }
5618            if (!(parent instanceof View)) {
5619                return true;
5620            }
5621            current = (View) parent;
5622        } while (current != null);
5623
5624        return false;
5625    }
5626
5627    /**
5628     * Called by the view hierarchy when the content insets for a window have
5629     * changed, to allow it to adjust its content to fit within those windows.
5630     * The content insets tell you the space that the status bar, input method,
5631     * and other system windows infringe on the application's window.
5632     *
5633     * <p>You do not normally need to deal with this function, since the default
5634     * window decoration given to applications takes care of applying it to the
5635     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5636     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5637     * and your content can be placed under those system elements.  You can then
5638     * use this method within your view hierarchy if you have parts of your UI
5639     * which you would like to ensure are not being covered.
5640     *
5641     * <p>The default implementation of this method simply applies the content
5642     * inset's to the view's padding, consuming that content (modifying the
5643     * insets to be 0), and returning true.  This behavior is off by default, but can
5644     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5645     *
5646     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5647     * insets object is propagated down the hierarchy, so any changes made to it will
5648     * be seen by all following views (including potentially ones above in
5649     * the hierarchy since this is a depth-first traversal).  The first view
5650     * that returns true will abort the entire traversal.
5651     *
5652     * <p>The default implementation works well for a situation where it is
5653     * used with a container that covers the entire window, allowing it to
5654     * apply the appropriate insets to its content on all edges.  If you need
5655     * a more complicated layout (such as two different views fitting system
5656     * windows, one on the top of the window, and one on the bottom),
5657     * you can override the method and handle the insets however you would like.
5658     * Note that the insets provided by the framework are always relative to the
5659     * far edges of the window, not accounting for the location of the called view
5660     * within that window.  (In fact when this method is called you do not yet know
5661     * where the layout will place the view, as it is done before layout happens.)
5662     *
5663     * <p>Note: unlike many View methods, there is no dispatch phase to this
5664     * call.  If you are overriding it in a ViewGroup and want to allow the
5665     * call to continue to your children, you must be sure to call the super
5666     * implementation.
5667     *
5668     * <p>Here is a sample layout that makes use of fitting system windows
5669     * to have controls for a video view placed inside of the window decorations
5670     * that it hides and shows.  This can be used with code like the second
5671     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5672     *
5673     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5674     *
5675     * @param insets Current content insets of the window.  Prior to
5676     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5677     * the insets or else you and Android will be unhappy.
5678     *
5679     * @return Return true if this view applied the insets and it should not
5680     * continue propagating further down the hierarchy, false otherwise.
5681     * @see #getFitsSystemWindows()
5682     * @see #setFitsSystemWindows(boolean)
5683     * @see #setSystemUiVisibility(int)
5684     */
5685    protected boolean fitSystemWindows(Rect insets) {
5686        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5687            mUserPaddingStart = UNDEFINED_PADDING;
5688            mUserPaddingEnd = UNDEFINED_PADDING;
5689            Rect localInsets = sThreadLocal.get();
5690            if (localInsets == null) {
5691                localInsets = new Rect();
5692                sThreadLocal.set(localInsets);
5693            }
5694            boolean res = computeFitSystemWindows(insets, localInsets);
5695            internalSetPadding(localInsets.left, localInsets.top,
5696                    localInsets.right, localInsets.bottom);
5697            return res;
5698        }
5699        return false;
5700    }
5701
5702    /**
5703     * @hide Compute the insets that should be consumed by this view and the ones
5704     * that should propagate to those under it.
5705     */
5706    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5707        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5708                || mAttachInfo == null
5709                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5710                        && !mAttachInfo.mOverscanRequested)) {
5711            outLocalInsets.set(inoutInsets);
5712            inoutInsets.set(0, 0, 0, 0);
5713            return true;
5714        } else {
5715            // The application wants to take care of fitting system window for
5716            // the content...  however we still need to take care of any overscan here.
5717            final Rect overscan = mAttachInfo.mOverscanInsets;
5718            outLocalInsets.set(overscan);
5719            inoutInsets.left -= overscan.left;
5720            inoutInsets.top -= overscan.top;
5721            inoutInsets.right -= overscan.right;
5722            inoutInsets.bottom -= overscan.bottom;
5723            return false;
5724        }
5725    }
5726
5727    /**
5728     * Sets whether or not this view should account for system screen decorations
5729     * such as the status bar and inset its content; that is, controlling whether
5730     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5731     * executed.  See that method for more details.
5732     *
5733     * <p>Note that if you are providing your own implementation of
5734     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5735     * flag to true -- your implementation will be overriding the default
5736     * implementation that checks this flag.
5737     *
5738     * @param fitSystemWindows If true, then the default implementation of
5739     * {@link #fitSystemWindows(Rect)} will be executed.
5740     *
5741     * @attr ref android.R.styleable#View_fitsSystemWindows
5742     * @see #getFitsSystemWindows()
5743     * @see #fitSystemWindows(Rect)
5744     * @see #setSystemUiVisibility(int)
5745     */
5746    public void setFitsSystemWindows(boolean fitSystemWindows) {
5747        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5748    }
5749
5750    /**
5751     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5752     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5753     * will be executed.
5754     *
5755     * @return Returns true if the default implementation of
5756     * {@link #fitSystemWindows(Rect)} will be executed.
5757     *
5758     * @attr ref android.R.styleable#View_fitsSystemWindows
5759     * @see #setFitsSystemWindows()
5760     * @see #fitSystemWindows(Rect)
5761     * @see #setSystemUiVisibility(int)
5762     */
5763    public boolean getFitsSystemWindows() {
5764        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5765    }
5766
5767    /** @hide */
5768    public boolean fitsSystemWindows() {
5769        return getFitsSystemWindows();
5770    }
5771
5772    /**
5773     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5774     */
5775    public void requestFitSystemWindows() {
5776        if (mParent != null) {
5777            mParent.requestFitSystemWindows();
5778        }
5779    }
5780
5781    /**
5782     * For use by PhoneWindow to make its own system window fitting optional.
5783     * @hide
5784     */
5785    public void makeOptionalFitsSystemWindows() {
5786        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5787    }
5788
5789    /**
5790     * Returns the visibility status for this view.
5791     *
5792     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5793     * @attr ref android.R.styleable#View_visibility
5794     */
5795    @ViewDebug.ExportedProperty(mapping = {
5796        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5797        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5798        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5799    })
5800    public int getVisibility() {
5801        return mViewFlags & VISIBILITY_MASK;
5802    }
5803
5804    /**
5805     * Set the enabled state of this view.
5806     *
5807     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5808     * @attr ref android.R.styleable#View_visibility
5809     */
5810    @RemotableViewMethod
5811    public void setVisibility(int visibility) {
5812        setFlags(visibility, VISIBILITY_MASK);
5813        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5814    }
5815
5816    /**
5817     * Returns the enabled status for this view. The interpretation of the
5818     * enabled state varies by subclass.
5819     *
5820     * @return True if this view is enabled, false otherwise.
5821     */
5822    @ViewDebug.ExportedProperty
5823    public boolean isEnabled() {
5824        return (mViewFlags & ENABLED_MASK) == ENABLED;
5825    }
5826
5827    /**
5828     * Set the enabled state of this view. The interpretation of the enabled
5829     * state varies by subclass.
5830     *
5831     * @param enabled True if this view is enabled, false otherwise.
5832     */
5833    @RemotableViewMethod
5834    public void setEnabled(boolean enabled) {
5835        if (enabled == isEnabled()) return;
5836
5837        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5838
5839        /*
5840         * The View most likely has to change its appearance, so refresh
5841         * the drawable state.
5842         */
5843        refreshDrawableState();
5844
5845        // Invalidate too, since the default behavior for views is to be
5846        // be drawn at 50% alpha rather than to change the drawable.
5847        invalidate(true);
5848    }
5849
5850    /**
5851     * Set whether this view can receive the focus.
5852     *
5853     * Setting this to false will also ensure that this view is not focusable
5854     * in touch mode.
5855     *
5856     * @param focusable If true, this view can receive the focus.
5857     *
5858     * @see #setFocusableInTouchMode(boolean)
5859     * @attr ref android.R.styleable#View_focusable
5860     */
5861    public void setFocusable(boolean focusable) {
5862        if (!focusable) {
5863            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5864        }
5865        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5866    }
5867
5868    /**
5869     * Set whether this view can receive focus while in touch mode.
5870     *
5871     * Setting this to true will also ensure that this view is focusable.
5872     *
5873     * @param focusableInTouchMode If true, this view can receive the focus while
5874     *   in touch mode.
5875     *
5876     * @see #setFocusable(boolean)
5877     * @attr ref android.R.styleable#View_focusableInTouchMode
5878     */
5879    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5880        // Focusable in touch mode should always be set before the focusable flag
5881        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5882        // which, in touch mode, will not successfully request focus on this view
5883        // because the focusable in touch mode flag is not set
5884        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5885        if (focusableInTouchMode) {
5886            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5887        }
5888    }
5889
5890    /**
5891     * Set whether this view should have sound effects enabled for events such as
5892     * clicking and touching.
5893     *
5894     * <p>You may wish to disable sound effects for a view if you already play sounds,
5895     * for instance, a dial key that plays dtmf tones.
5896     *
5897     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5898     * @see #isSoundEffectsEnabled()
5899     * @see #playSoundEffect(int)
5900     * @attr ref android.R.styleable#View_soundEffectsEnabled
5901     */
5902    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5903        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5904    }
5905
5906    /**
5907     * @return whether this view should have sound effects enabled for events such as
5908     *     clicking and touching.
5909     *
5910     * @see #setSoundEffectsEnabled(boolean)
5911     * @see #playSoundEffect(int)
5912     * @attr ref android.R.styleable#View_soundEffectsEnabled
5913     */
5914    @ViewDebug.ExportedProperty
5915    public boolean isSoundEffectsEnabled() {
5916        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5917    }
5918
5919    /**
5920     * Set whether this view should have haptic feedback for events such as
5921     * long presses.
5922     *
5923     * <p>You may wish to disable haptic feedback if your view already controls
5924     * its own haptic feedback.
5925     *
5926     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5927     * @see #isHapticFeedbackEnabled()
5928     * @see #performHapticFeedback(int)
5929     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5930     */
5931    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5932        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5933    }
5934
5935    /**
5936     * @return whether this view should have haptic feedback enabled for events
5937     * long presses.
5938     *
5939     * @see #setHapticFeedbackEnabled(boolean)
5940     * @see #performHapticFeedback(int)
5941     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5942     */
5943    @ViewDebug.ExportedProperty
5944    public boolean isHapticFeedbackEnabled() {
5945        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5946    }
5947
5948    /**
5949     * Returns the layout direction for this view.
5950     *
5951     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5952     *   {@link #LAYOUT_DIRECTION_RTL},
5953     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5954     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5955     *
5956     * @attr ref android.R.styleable#View_layoutDirection
5957     *
5958     * @hide
5959     */
5960    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5961        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5962        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5963        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5964        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5965    })
5966    public int getRawLayoutDirection() {
5967        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
5968    }
5969
5970    /**
5971     * Set the layout direction for this view. This will propagate a reset of layout direction
5972     * resolution to the view's children and resolve layout direction for this view.
5973     *
5974     * @param layoutDirection the layout direction to set. Should be one of:
5975     *
5976     * {@link #LAYOUT_DIRECTION_LTR},
5977     * {@link #LAYOUT_DIRECTION_RTL},
5978     * {@link #LAYOUT_DIRECTION_INHERIT},
5979     * {@link #LAYOUT_DIRECTION_LOCALE}.
5980     *
5981     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
5982     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
5983     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
5984     *
5985     * @attr ref android.R.styleable#View_layoutDirection
5986     */
5987    @RemotableViewMethod
5988    public void setLayoutDirection(int layoutDirection) {
5989        if (getRawLayoutDirection() != layoutDirection) {
5990            // Reset the current layout direction and the resolved one
5991            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
5992            resetRtlProperties();
5993            // Set the new layout direction (filtered)
5994            mPrivateFlags2 |=
5995                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
5996            // We need to resolve all RTL properties as they all depend on layout direction
5997            resolveRtlPropertiesIfNeeded();
5998            requestLayout();
5999            invalidate(true);
6000        }
6001    }
6002
6003    /**
6004     * Returns the resolved layout direction for this view.
6005     *
6006     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6007     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6008     *
6009     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6010     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6011     *
6012     * @attr ref android.R.styleable#View_layoutDirection
6013     */
6014    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6015        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6016        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6017    })
6018    public int getLayoutDirection() {
6019        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6020        if (targetSdkVersion < JELLY_BEAN_MR1) {
6021            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6022            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6023        }
6024        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6025                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6026    }
6027
6028    /**
6029     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6030     * layout attribute and/or the inherited value from the parent
6031     *
6032     * @return true if the layout is right-to-left.
6033     *
6034     * @hide
6035     */
6036    @ViewDebug.ExportedProperty(category = "layout")
6037    public boolean isLayoutRtl() {
6038        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6039    }
6040
6041    /**
6042     * Indicates whether the view is currently tracking transient state that the
6043     * app should not need to concern itself with saving and restoring, but that
6044     * the framework should take special note to preserve when possible.
6045     *
6046     * <p>A view with transient state cannot be trivially rebound from an external
6047     * data source, such as an adapter binding item views in a list. This may be
6048     * because the view is performing an animation, tracking user selection
6049     * of content, or similar.</p>
6050     *
6051     * @return true if the view has transient state
6052     */
6053    @ViewDebug.ExportedProperty(category = "layout")
6054    public boolean hasTransientState() {
6055        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6056    }
6057
6058    /**
6059     * Set whether this view is currently tracking transient state that the
6060     * framework should attempt to preserve when possible. This flag is reference counted,
6061     * so every call to setHasTransientState(true) should be paired with a later call
6062     * to setHasTransientState(false).
6063     *
6064     * <p>A view with transient state cannot be trivially rebound from an external
6065     * data source, such as an adapter binding item views in a list. This may be
6066     * because the view is performing an animation, tracking user selection
6067     * of content, or similar.</p>
6068     *
6069     * @param hasTransientState true if this view has transient state
6070     */
6071    public void setHasTransientState(boolean hasTransientState) {
6072        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6073                mTransientStateCount - 1;
6074        if (mTransientStateCount < 0) {
6075            mTransientStateCount = 0;
6076            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6077                    "unmatched pair of setHasTransientState calls");
6078        } else if ((hasTransientState && mTransientStateCount == 1) ||
6079                (!hasTransientState && mTransientStateCount == 0)) {
6080            // update flag if we've just incremented up from 0 or decremented down to 0
6081            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6082                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6083            if (mParent != null) {
6084                try {
6085                    mParent.childHasTransientStateChanged(this, hasTransientState);
6086                } catch (AbstractMethodError e) {
6087                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6088                            " does not fully implement ViewParent", e);
6089                }
6090            }
6091        }
6092    }
6093
6094    /**
6095     * If this view doesn't do any drawing on its own, set this flag to
6096     * allow further optimizations. By default, this flag is not set on
6097     * View, but could be set on some View subclasses such as ViewGroup.
6098     *
6099     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6100     * you should clear this flag.
6101     *
6102     * @param willNotDraw whether or not this View draw on its own
6103     */
6104    public void setWillNotDraw(boolean willNotDraw) {
6105        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6106    }
6107
6108    /**
6109     * Returns whether or not this View draws on its own.
6110     *
6111     * @return true if this view has nothing to draw, false otherwise
6112     */
6113    @ViewDebug.ExportedProperty(category = "drawing")
6114    public boolean willNotDraw() {
6115        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6116    }
6117
6118    /**
6119     * When a View's drawing cache is enabled, drawing is redirected to an
6120     * offscreen bitmap. Some views, like an ImageView, must be able to
6121     * bypass this mechanism if they already draw a single bitmap, to avoid
6122     * unnecessary usage of the memory.
6123     *
6124     * @param willNotCacheDrawing true if this view does not cache its
6125     *        drawing, false otherwise
6126     */
6127    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6128        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6129    }
6130
6131    /**
6132     * Returns whether or not this View can cache its drawing or not.
6133     *
6134     * @return true if this view does not cache its drawing, false otherwise
6135     */
6136    @ViewDebug.ExportedProperty(category = "drawing")
6137    public boolean willNotCacheDrawing() {
6138        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6139    }
6140
6141    /**
6142     * Indicates whether this view reacts to click events or not.
6143     *
6144     * @return true if the view is clickable, false otherwise
6145     *
6146     * @see #setClickable(boolean)
6147     * @attr ref android.R.styleable#View_clickable
6148     */
6149    @ViewDebug.ExportedProperty
6150    public boolean isClickable() {
6151        return (mViewFlags & CLICKABLE) == CLICKABLE;
6152    }
6153
6154    /**
6155     * Enables or disables click events for this view. When a view
6156     * is clickable it will change its state to "pressed" on every click.
6157     * Subclasses should set the view clickable to visually react to
6158     * user's clicks.
6159     *
6160     * @param clickable true to make the view clickable, false otherwise
6161     *
6162     * @see #isClickable()
6163     * @attr ref android.R.styleable#View_clickable
6164     */
6165    public void setClickable(boolean clickable) {
6166        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6167    }
6168
6169    /**
6170     * Indicates whether this view reacts to long click events or not.
6171     *
6172     * @return true if the view is long clickable, false otherwise
6173     *
6174     * @see #setLongClickable(boolean)
6175     * @attr ref android.R.styleable#View_longClickable
6176     */
6177    public boolean isLongClickable() {
6178        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6179    }
6180
6181    /**
6182     * Enables or disables long click events for this view. When a view is long
6183     * clickable it reacts to the user holding down the button for a longer
6184     * duration than a tap. This event can either launch the listener or a
6185     * context menu.
6186     *
6187     * @param longClickable true to make the view long clickable, false otherwise
6188     * @see #isLongClickable()
6189     * @attr ref android.R.styleable#View_longClickable
6190     */
6191    public void setLongClickable(boolean longClickable) {
6192        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6193    }
6194
6195    /**
6196     * Sets the pressed state for this view.
6197     *
6198     * @see #isClickable()
6199     * @see #setClickable(boolean)
6200     *
6201     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6202     *        the View's internal state from a previously set "pressed" state.
6203     */
6204    public void setPressed(boolean pressed) {
6205        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6206
6207        if (pressed) {
6208            mPrivateFlags |= PFLAG_PRESSED;
6209        } else {
6210            mPrivateFlags &= ~PFLAG_PRESSED;
6211        }
6212
6213        if (needsRefresh) {
6214            refreshDrawableState();
6215        }
6216        dispatchSetPressed(pressed);
6217    }
6218
6219    /**
6220     * Dispatch setPressed to all of this View's children.
6221     *
6222     * @see #setPressed(boolean)
6223     *
6224     * @param pressed The new pressed state
6225     */
6226    protected void dispatchSetPressed(boolean pressed) {
6227    }
6228
6229    /**
6230     * Indicates whether the view is currently in pressed state. Unless
6231     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6232     * the pressed state.
6233     *
6234     * @see #setPressed(boolean)
6235     * @see #isClickable()
6236     * @see #setClickable(boolean)
6237     *
6238     * @return true if the view is currently pressed, false otherwise
6239     */
6240    public boolean isPressed() {
6241        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6242    }
6243
6244    /**
6245     * Indicates whether this view will save its state (that is,
6246     * whether its {@link #onSaveInstanceState} method will be called).
6247     *
6248     * @return Returns true if the view state saving is enabled, else false.
6249     *
6250     * @see #setSaveEnabled(boolean)
6251     * @attr ref android.R.styleable#View_saveEnabled
6252     */
6253    public boolean isSaveEnabled() {
6254        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6255    }
6256
6257    /**
6258     * Controls whether the saving of this view's state is
6259     * enabled (that is, whether its {@link #onSaveInstanceState} method
6260     * will be called).  Note that even if freezing is enabled, the
6261     * view still must have an id assigned to it (via {@link #setId(int)})
6262     * for its state to be saved.  This flag can only disable the
6263     * saving of this view; any child views may still have their state saved.
6264     *
6265     * @param enabled Set to false to <em>disable</em> state saving, or true
6266     * (the default) to allow it.
6267     *
6268     * @see #isSaveEnabled()
6269     * @see #setId(int)
6270     * @see #onSaveInstanceState()
6271     * @attr ref android.R.styleable#View_saveEnabled
6272     */
6273    public void setSaveEnabled(boolean enabled) {
6274        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6275    }
6276
6277    /**
6278     * Gets whether the framework should discard touches when the view's
6279     * window is obscured by another visible window.
6280     * Refer to the {@link View} security documentation for more details.
6281     *
6282     * @return True if touch filtering is enabled.
6283     *
6284     * @see #setFilterTouchesWhenObscured(boolean)
6285     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6286     */
6287    @ViewDebug.ExportedProperty
6288    public boolean getFilterTouchesWhenObscured() {
6289        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6290    }
6291
6292    /**
6293     * Sets whether the framework should discard touches when the view's
6294     * window is obscured by another visible window.
6295     * Refer to the {@link View} security documentation for more details.
6296     *
6297     * @param enabled True if touch filtering should be enabled.
6298     *
6299     * @see #getFilterTouchesWhenObscured
6300     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6301     */
6302    public void setFilterTouchesWhenObscured(boolean enabled) {
6303        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6304                FILTER_TOUCHES_WHEN_OBSCURED);
6305    }
6306
6307    /**
6308     * Indicates whether the entire hierarchy under this view will save its
6309     * state when a state saving traversal occurs from its parent.  The default
6310     * is true; if false, these views will not be saved unless
6311     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6312     *
6313     * @return Returns true if the view state saving from parent is enabled, else false.
6314     *
6315     * @see #setSaveFromParentEnabled(boolean)
6316     */
6317    public boolean isSaveFromParentEnabled() {
6318        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6319    }
6320
6321    /**
6322     * Controls whether the entire hierarchy under this view will save its
6323     * state when a state saving traversal occurs from its parent.  The default
6324     * is true; if false, these views will not be saved unless
6325     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6326     *
6327     * @param enabled Set to false to <em>disable</em> state saving, or true
6328     * (the default) to allow it.
6329     *
6330     * @see #isSaveFromParentEnabled()
6331     * @see #setId(int)
6332     * @see #onSaveInstanceState()
6333     */
6334    public void setSaveFromParentEnabled(boolean enabled) {
6335        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6336    }
6337
6338
6339    /**
6340     * Returns whether this View is able to take focus.
6341     *
6342     * @return True if this view can take focus, or false otherwise.
6343     * @attr ref android.R.styleable#View_focusable
6344     */
6345    @ViewDebug.ExportedProperty(category = "focus")
6346    public final boolean isFocusable() {
6347        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6348    }
6349
6350    /**
6351     * When a view is focusable, it may not want to take focus when in touch mode.
6352     * For example, a button would like focus when the user is navigating via a D-pad
6353     * so that the user can click on it, but once the user starts touching the screen,
6354     * the button shouldn't take focus
6355     * @return Whether the view is focusable in touch mode.
6356     * @attr ref android.R.styleable#View_focusableInTouchMode
6357     */
6358    @ViewDebug.ExportedProperty
6359    public final boolean isFocusableInTouchMode() {
6360        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6361    }
6362
6363    /**
6364     * Find the nearest view in the specified direction that can take focus.
6365     * This does not actually give focus to that view.
6366     *
6367     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6368     *
6369     * @return The nearest focusable in the specified direction, or null if none
6370     *         can be found.
6371     */
6372    public View focusSearch(int direction) {
6373        if (mParent != null) {
6374            return mParent.focusSearch(this, direction);
6375        } else {
6376            return null;
6377        }
6378    }
6379
6380    /**
6381     * This method is the last chance for the focused view and its ancestors to
6382     * respond to an arrow key. This is called when the focused view did not
6383     * consume the key internally, nor could the view system find a new view in
6384     * the requested direction to give focus to.
6385     *
6386     * @param focused The currently focused view.
6387     * @param direction The direction focus wants to move. One of FOCUS_UP,
6388     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6389     * @return True if the this view consumed this unhandled move.
6390     */
6391    public boolean dispatchUnhandledMove(View focused, int direction) {
6392        return false;
6393    }
6394
6395    /**
6396     * If a user manually specified the next view id for a particular direction,
6397     * use the root to look up the view.
6398     * @param root The root view of the hierarchy containing this view.
6399     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6400     * or FOCUS_BACKWARD.
6401     * @return The user specified next view, or null if there is none.
6402     */
6403    View findUserSetNextFocus(View root, int direction) {
6404        switch (direction) {
6405            case FOCUS_LEFT:
6406                if (mNextFocusLeftId == View.NO_ID) return null;
6407                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6408            case FOCUS_RIGHT:
6409                if (mNextFocusRightId == View.NO_ID) return null;
6410                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6411            case FOCUS_UP:
6412                if (mNextFocusUpId == View.NO_ID) return null;
6413                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6414            case FOCUS_DOWN:
6415                if (mNextFocusDownId == View.NO_ID) return null;
6416                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6417            case FOCUS_FORWARD:
6418                if (mNextFocusForwardId == View.NO_ID) return null;
6419                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6420            case FOCUS_BACKWARD: {
6421                if (mID == View.NO_ID) return null;
6422                final int id = mID;
6423                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6424                    @Override
6425                    public boolean apply(View t) {
6426                        return t.mNextFocusForwardId == id;
6427                    }
6428                });
6429            }
6430        }
6431        return null;
6432    }
6433
6434    private View findViewInsideOutShouldExist(View root, int id) {
6435        if (mMatchIdPredicate == null) {
6436            mMatchIdPredicate = new MatchIdPredicate();
6437        }
6438        mMatchIdPredicate.mId = id;
6439        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6440        if (result == null) {
6441            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6442        }
6443        return result;
6444    }
6445
6446    /**
6447     * Find and return all focusable views that are descendants of this view,
6448     * possibly including this view if it is focusable itself.
6449     *
6450     * @param direction The direction of the focus
6451     * @return A list of focusable views
6452     */
6453    public ArrayList<View> getFocusables(int direction) {
6454        ArrayList<View> result = new ArrayList<View>(24);
6455        addFocusables(result, direction);
6456        return result;
6457    }
6458
6459    /**
6460     * Add any focusable views that are descendants of this view (possibly
6461     * including this view if it is focusable itself) to views.  If we are in touch mode,
6462     * only add views that are also focusable in touch mode.
6463     *
6464     * @param views Focusable views found so far
6465     * @param direction The direction of the focus
6466     */
6467    public void addFocusables(ArrayList<View> views, int direction) {
6468        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6469    }
6470
6471    /**
6472     * Adds any focusable views that are descendants of this view (possibly
6473     * including this view if it is focusable itself) to views. This method
6474     * adds all focusable views regardless if we are in touch mode or
6475     * only views focusable in touch mode if we are in touch mode or
6476     * only views that can take accessibility focus if accessibility is enabeld
6477     * depending on the focusable mode paramater.
6478     *
6479     * @param views Focusable views found so far or null if all we are interested is
6480     *        the number of focusables.
6481     * @param direction The direction of the focus.
6482     * @param focusableMode The type of focusables to be added.
6483     *
6484     * @see #FOCUSABLES_ALL
6485     * @see #FOCUSABLES_TOUCH_MODE
6486     */
6487    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6488        if (views == null) {
6489            return;
6490        }
6491        if (!isFocusable()) {
6492            return;
6493        }
6494        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6495                && isInTouchMode() && !isFocusableInTouchMode()) {
6496            return;
6497        }
6498        views.add(this);
6499    }
6500
6501    /**
6502     * Finds the Views that contain given text. The containment is case insensitive.
6503     * The search is performed by either the text that the View renders or the content
6504     * description that describes the view for accessibility purposes and the view does
6505     * not render or both. Clients can specify how the search is to be performed via
6506     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6507     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6508     *
6509     * @param outViews The output list of matching Views.
6510     * @param searched The text to match against.
6511     *
6512     * @see #FIND_VIEWS_WITH_TEXT
6513     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6514     * @see #setContentDescription(CharSequence)
6515     */
6516    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6517        if (getAccessibilityNodeProvider() != null) {
6518            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6519                outViews.add(this);
6520            }
6521        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6522                && (searched != null && searched.length() > 0)
6523                && (mContentDescription != null && mContentDescription.length() > 0)) {
6524            String searchedLowerCase = searched.toString().toLowerCase();
6525            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6526            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6527                outViews.add(this);
6528            }
6529        }
6530    }
6531
6532    /**
6533     * Find and return all touchable views that are descendants of this view,
6534     * possibly including this view if it is touchable itself.
6535     *
6536     * @return A list of touchable views
6537     */
6538    public ArrayList<View> getTouchables() {
6539        ArrayList<View> result = new ArrayList<View>();
6540        addTouchables(result);
6541        return result;
6542    }
6543
6544    /**
6545     * Add any touchable views that are descendants of this view (possibly
6546     * including this view if it is touchable itself) to views.
6547     *
6548     * @param views Touchable views found so far
6549     */
6550    public void addTouchables(ArrayList<View> views) {
6551        final int viewFlags = mViewFlags;
6552
6553        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6554                && (viewFlags & ENABLED_MASK) == ENABLED) {
6555            views.add(this);
6556        }
6557    }
6558
6559    /**
6560     * Returns whether this View is accessibility focused.
6561     *
6562     * @return True if this View is accessibility focused.
6563     */
6564    boolean isAccessibilityFocused() {
6565        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6566    }
6567
6568    /**
6569     * Call this to try to give accessibility focus to this view.
6570     *
6571     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6572     * returns false or the view is no visible or the view already has accessibility
6573     * focus.
6574     *
6575     * See also {@link #focusSearch(int)}, which is what you call to say that you
6576     * have focus, and you want your parent to look for the next one.
6577     *
6578     * @return Whether this view actually took accessibility focus.
6579     *
6580     * @hide
6581     */
6582    public boolean requestAccessibilityFocus() {
6583        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6584        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6585            return false;
6586        }
6587        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6588            return false;
6589        }
6590        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6591            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6592            ViewRootImpl viewRootImpl = getViewRootImpl();
6593            if (viewRootImpl != null) {
6594                viewRootImpl.setAccessibilityFocus(this, null);
6595            }
6596            invalidate();
6597            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6598            notifyAccessibilityStateChanged();
6599            return true;
6600        }
6601        return false;
6602    }
6603
6604    /**
6605     * Call this to try to clear accessibility focus of this view.
6606     *
6607     * See also {@link #focusSearch(int)}, which is what you call to say that you
6608     * have focus, and you want your parent to look for the next one.
6609     *
6610     * @hide
6611     */
6612    public void clearAccessibilityFocus() {
6613        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6614            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6615            invalidate();
6616            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6617            notifyAccessibilityStateChanged();
6618        }
6619        // Clear the global reference of accessibility focus if this
6620        // view or any of its descendants had accessibility focus.
6621        ViewRootImpl viewRootImpl = getViewRootImpl();
6622        if (viewRootImpl != null) {
6623            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6624            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6625                viewRootImpl.setAccessibilityFocus(null, null);
6626            }
6627        }
6628    }
6629
6630    private void sendAccessibilityHoverEvent(int eventType) {
6631        // Since we are not delivering to a client accessibility events from not
6632        // important views (unless the clinet request that) we need to fire the
6633        // event from the deepest view exposed to the client. As a consequence if
6634        // the user crosses a not exposed view the client will see enter and exit
6635        // of the exposed predecessor followed by and enter and exit of that same
6636        // predecessor when entering and exiting the not exposed descendant. This
6637        // is fine since the client has a clear idea which view is hovered at the
6638        // price of a couple more events being sent. This is a simple and
6639        // working solution.
6640        View source = this;
6641        while (true) {
6642            if (source.includeForAccessibility()) {
6643                source.sendAccessibilityEvent(eventType);
6644                return;
6645            }
6646            ViewParent parent = source.getParent();
6647            if (parent instanceof View) {
6648                source = (View) parent;
6649            } else {
6650                return;
6651            }
6652        }
6653    }
6654
6655    /**
6656     * Clears accessibility focus without calling any callback methods
6657     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6658     * is used for clearing accessibility focus when giving this focus to
6659     * another view.
6660     */
6661    void clearAccessibilityFocusNoCallbacks() {
6662        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6663            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6664            invalidate();
6665        }
6666    }
6667
6668    /**
6669     * Call this to try to give focus to a specific view or to one of its
6670     * descendants.
6671     *
6672     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6673     * false), or if it is focusable and it is not focusable in touch mode
6674     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6675     *
6676     * See also {@link #focusSearch(int)}, which is what you call to say that you
6677     * have focus, and you want your parent to look for the next one.
6678     *
6679     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6680     * {@link #FOCUS_DOWN} and <code>null</code>.
6681     *
6682     * @return Whether this view or one of its descendants actually took focus.
6683     */
6684    public final boolean requestFocus() {
6685        return requestFocus(View.FOCUS_DOWN);
6686    }
6687
6688    /**
6689     * Call this to try to give focus to a specific view or to one of its
6690     * descendants and give it a hint about what direction focus is heading.
6691     *
6692     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6693     * false), or if it is focusable and it is not focusable in touch mode
6694     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6695     *
6696     * See also {@link #focusSearch(int)}, which is what you call to say that you
6697     * have focus, and you want your parent to look for the next one.
6698     *
6699     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6700     * <code>null</code> set for the previously focused rectangle.
6701     *
6702     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6703     * @return Whether this view or one of its descendants actually took focus.
6704     */
6705    public final boolean requestFocus(int direction) {
6706        return requestFocus(direction, null);
6707    }
6708
6709    /**
6710     * Call this to try to give focus to a specific view or to one of its descendants
6711     * and give it hints about the direction and a specific rectangle that the focus
6712     * is coming from.  The rectangle can help give larger views a finer grained hint
6713     * about where focus is coming from, and therefore, where to show selection, or
6714     * forward focus change internally.
6715     *
6716     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6717     * false), or if it is focusable and it is not focusable in touch mode
6718     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6719     *
6720     * A View will not take focus if it is not visible.
6721     *
6722     * A View will not take focus if one of its parents has
6723     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6724     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6725     *
6726     * See also {@link #focusSearch(int)}, which is what you call to say that you
6727     * have focus, and you want your parent to look for the next one.
6728     *
6729     * You may wish to override this method if your custom {@link View} has an internal
6730     * {@link View} that it wishes to forward the request to.
6731     *
6732     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6733     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6734     *        to give a finer grained hint about where focus is coming from.  May be null
6735     *        if there is no hint.
6736     * @return Whether this view or one of its descendants actually took focus.
6737     */
6738    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6739        return requestFocusNoSearch(direction, previouslyFocusedRect);
6740    }
6741
6742    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6743        // need to be focusable
6744        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6745                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6746            return false;
6747        }
6748
6749        // need to be focusable in touch mode if in touch mode
6750        if (isInTouchMode() &&
6751            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6752               return false;
6753        }
6754
6755        // need to not have any parents blocking us
6756        if (hasAncestorThatBlocksDescendantFocus()) {
6757            return false;
6758        }
6759
6760        handleFocusGainInternal(direction, previouslyFocusedRect);
6761        return true;
6762    }
6763
6764    /**
6765     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6766     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6767     * touch mode to request focus when they are touched.
6768     *
6769     * @return Whether this view or one of its descendants actually took focus.
6770     *
6771     * @see #isInTouchMode()
6772     *
6773     */
6774    public final boolean requestFocusFromTouch() {
6775        // Leave touch mode if we need to
6776        if (isInTouchMode()) {
6777            ViewRootImpl viewRoot = getViewRootImpl();
6778            if (viewRoot != null) {
6779                viewRoot.ensureTouchMode(false);
6780            }
6781        }
6782        return requestFocus(View.FOCUS_DOWN);
6783    }
6784
6785    /**
6786     * @return Whether any ancestor of this view blocks descendant focus.
6787     */
6788    private boolean hasAncestorThatBlocksDescendantFocus() {
6789        ViewParent ancestor = mParent;
6790        while (ancestor instanceof ViewGroup) {
6791            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6792            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6793                return true;
6794            } else {
6795                ancestor = vgAncestor.getParent();
6796            }
6797        }
6798        return false;
6799    }
6800
6801    /**
6802     * Gets the mode for determining whether this View is important for accessibility
6803     * which is if it fires accessibility events and if it is reported to
6804     * accessibility services that query the screen.
6805     *
6806     * @return The mode for determining whether a View is important for accessibility.
6807     *
6808     * @attr ref android.R.styleable#View_importantForAccessibility
6809     *
6810     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6811     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6812     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6813     */
6814    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6815            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6816            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6817            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6818        })
6819    public int getImportantForAccessibility() {
6820        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6821                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6822    }
6823
6824    /**
6825     * Sets how to determine whether this view is important for accessibility
6826     * which is if it fires accessibility events and if it is reported to
6827     * accessibility services that query the screen.
6828     *
6829     * @param mode How to determine whether this view is important for accessibility.
6830     *
6831     * @attr ref android.R.styleable#View_importantForAccessibility
6832     *
6833     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6834     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6835     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6836     */
6837    public void setImportantForAccessibility(int mode) {
6838        if (mode != getImportantForAccessibility()) {
6839            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6840            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6841                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6842            notifyAccessibilityStateChanged();
6843        }
6844    }
6845
6846    /**
6847     * Gets whether this view should be exposed for accessibility.
6848     *
6849     * @return Whether the view is exposed for accessibility.
6850     *
6851     * @hide
6852     */
6853    public boolean isImportantForAccessibility() {
6854        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6855                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6856        switch (mode) {
6857            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6858                return true;
6859            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6860                return false;
6861            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6862                return isActionableForAccessibility() || hasListenersForAccessibility()
6863                        || getAccessibilityNodeProvider() != null;
6864            default:
6865                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6866                        + mode);
6867        }
6868    }
6869
6870    /**
6871     * Gets the parent for accessibility purposes. Note that the parent for
6872     * accessibility is not necessary the immediate parent. It is the first
6873     * predecessor that is important for accessibility.
6874     *
6875     * @return The parent for accessibility purposes.
6876     */
6877    public ViewParent getParentForAccessibility() {
6878        if (mParent instanceof View) {
6879            View parentView = (View) mParent;
6880            if (parentView.includeForAccessibility()) {
6881                return mParent;
6882            } else {
6883                return mParent.getParentForAccessibility();
6884            }
6885        }
6886        return null;
6887    }
6888
6889    /**
6890     * Adds the children of a given View for accessibility. Since some Views are
6891     * not important for accessibility the children for accessibility are not
6892     * necessarily direct children of the view, rather they are the first level of
6893     * descendants important for accessibility.
6894     *
6895     * @param children The list of children for accessibility.
6896     */
6897    public void addChildrenForAccessibility(ArrayList<View> children) {
6898        if (includeForAccessibility()) {
6899            children.add(this);
6900        }
6901    }
6902
6903    /**
6904     * Whether to regard this view for accessibility. A view is regarded for
6905     * accessibility if it is important for accessibility or the querying
6906     * accessibility service has explicitly requested that view not
6907     * important for accessibility are regarded.
6908     *
6909     * @return Whether to regard the view for accessibility.
6910     *
6911     * @hide
6912     */
6913    public boolean includeForAccessibility() {
6914        if (mAttachInfo != null) {
6915            return (mAttachInfo.mAccessibilityFetchFlags
6916                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
6917                    || isImportantForAccessibility();
6918        }
6919        return false;
6920    }
6921
6922    /**
6923     * Returns whether the View is considered actionable from
6924     * accessibility perspective. Such view are important for
6925     * accessibility.
6926     *
6927     * @return True if the view is actionable for accessibility.
6928     *
6929     * @hide
6930     */
6931    public boolean isActionableForAccessibility() {
6932        return (isClickable() || isLongClickable() || isFocusable());
6933    }
6934
6935    /**
6936     * Returns whether the View has registered callbacks wich makes it
6937     * important for accessibility.
6938     *
6939     * @return True if the view is actionable for accessibility.
6940     */
6941    private boolean hasListenersForAccessibility() {
6942        ListenerInfo info = getListenerInfo();
6943        return mTouchDelegate != null || info.mOnKeyListener != null
6944                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6945                || info.mOnHoverListener != null || info.mOnDragListener != null;
6946    }
6947
6948    /**
6949     * Notifies accessibility services that some view's important for
6950     * accessibility state has changed. Note that such notifications
6951     * are made at most once every
6952     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6953     * to avoid unnecessary load to the system. Also once a view has
6954     * made a notifucation this method is a NOP until the notification has
6955     * been sent to clients.
6956     *
6957     * @hide
6958     *
6959     * TODO: Makse sure this method is called for any view state change
6960     *       that is interesting for accessilility purposes.
6961     */
6962    public void notifyAccessibilityStateChanged() {
6963        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6964            return;
6965        }
6966        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6967            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6968            if (mParent != null) {
6969                mParent.childAccessibilityStateChanged(this);
6970            }
6971        }
6972    }
6973
6974    /**
6975     * Reset the state indicating the this view has requested clients
6976     * interested in its accessibility state to be notified.
6977     *
6978     * @hide
6979     */
6980    public void resetAccessibilityStateChanged() {
6981        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6982    }
6983
6984    /**
6985     * Performs the specified accessibility action on the view. For
6986     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6987     * <p>
6988     * If an {@link AccessibilityDelegate} has been specified via calling
6989     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6990     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6991     * is responsible for handling this call.
6992     * </p>
6993     *
6994     * @param action The action to perform.
6995     * @param arguments Optional action arguments.
6996     * @return Whether the action was performed.
6997     */
6998    public boolean performAccessibilityAction(int action, Bundle arguments) {
6999      if (mAccessibilityDelegate != null) {
7000          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
7001      } else {
7002          return performAccessibilityActionInternal(action, arguments);
7003      }
7004    }
7005
7006   /**
7007    * @see #performAccessibilityAction(int, Bundle)
7008    *
7009    * Note: Called from the default {@link AccessibilityDelegate}.
7010    */
7011    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7012        switch (action) {
7013            case AccessibilityNodeInfo.ACTION_CLICK: {
7014                if (isClickable()) {
7015                    performClick();
7016                    return true;
7017                }
7018            } break;
7019            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7020                if (isLongClickable()) {
7021                    performLongClick();
7022                    return true;
7023                }
7024            } break;
7025            case AccessibilityNodeInfo.ACTION_FOCUS: {
7026                if (!hasFocus()) {
7027                    // Get out of touch mode since accessibility
7028                    // wants to move focus around.
7029                    getViewRootImpl().ensureTouchMode(false);
7030                    return requestFocus();
7031                }
7032            } break;
7033            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7034                if (hasFocus()) {
7035                    clearFocus();
7036                    return !isFocused();
7037                }
7038            } break;
7039            case AccessibilityNodeInfo.ACTION_SELECT: {
7040                if (!isSelected()) {
7041                    setSelected(true);
7042                    return isSelected();
7043                }
7044            } break;
7045            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7046                if (isSelected()) {
7047                    setSelected(false);
7048                    return !isSelected();
7049                }
7050            } break;
7051            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7052                if (!isAccessibilityFocused()) {
7053                    return requestAccessibilityFocus();
7054                }
7055            } break;
7056            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7057                if (isAccessibilityFocused()) {
7058                    clearAccessibilityFocus();
7059                    return true;
7060                }
7061            } break;
7062            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7063                if (arguments != null) {
7064                    final int granularity = arguments.getInt(
7065                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7066                    final boolean extendSelection = arguments.getBoolean(
7067                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7068                    return nextAtGranularity(granularity, extendSelection);
7069                }
7070            } break;
7071            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7072                if (arguments != null) {
7073                    final int granularity = arguments.getInt(
7074                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7075                    final boolean extendSelection = arguments.getBoolean(
7076                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7077                    return previousAtGranularity(granularity, extendSelection);
7078                }
7079            } break;
7080            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7081                CharSequence text = getIterableTextForAccessibility();
7082                if (text == null) {
7083                    return false;
7084                }
7085                final int start = (arguments != null) ? arguments.getInt(
7086                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7087                final int end = (arguments != null) ? arguments.getInt(
7088                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7089                // Only cursor position can be specified (selection length == 0)
7090                if ((getAccessibilitySelectionStart() != start
7091                        || getAccessibilitySelectionEnd() != end)
7092                        && (start == end)) {
7093                    setAccessibilitySelection(start, end);
7094                    notifyAccessibilityStateChanged();
7095                    return true;
7096                }
7097            } break;
7098        }
7099        return false;
7100    }
7101
7102    private boolean nextAtGranularity(int granularity, boolean extendSelection) {
7103        CharSequence text = getIterableTextForAccessibility();
7104        if (text == null || text.length() == 0) {
7105            return false;
7106        }
7107        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7108        if (iterator == null) {
7109            return false;
7110        }
7111        int current = getAccessibilitySelectionEnd();
7112        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7113            current = 0;
7114        }
7115        final int[] range = iterator.following(current);
7116        if (range == null) {
7117            return false;
7118        }
7119        final int start = range[0];
7120        final int end = range[1];
7121        if (extendSelection && isAccessibilitySelectionExtendable()) {
7122            int selectionStart = getAccessibilitySelectionStart();
7123            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7124                selectionStart = start;
7125            }
7126            setAccessibilitySelection(selectionStart, end);
7127        } else {
7128            setAccessibilitySelection(end, end);
7129        }
7130        sendViewTextTraversedAtGranularityEvent(
7131                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
7132                granularity, start, end);
7133        return true;
7134    }
7135
7136    private boolean previousAtGranularity(int granularity, boolean extendSelection) {
7137        CharSequence text = getIterableTextForAccessibility();
7138        if (text == null || text.length() == 0) {
7139            return false;
7140        }
7141        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7142        if (iterator == null) {
7143            return false;
7144        }
7145        int current = getAccessibilitySelectionStart();
7146        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7147            current = text.length();
7148        }
7149        final int[] range = iterator.preceding(current);
7150        if (range == null) {
7151            return false;
7152        }
7153        final int start = range[0];
7154        final int end = range[1];
7155        if (extendSelection && isAccessibilitySelectionExtendable()) {
7156            int selectionEnd = getAccessibilitySelectionEnd();
7157            if (selectionEnd == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7158                selectionEnd = end;
7159            }
7160            setAccessibilitySelection(start, selectionEnd);
7161        } else {
7162            setAccessibilitySelection(start, start);
7163        }
7164        sendViewTextTraversedAtGranularityEvent(
7165                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
7166                granularity, start, end);
7167        return true;
7168    }
7169
7170    /**
7171     * Gets the text reported for accessibility purposes.
7172     *
7173     * @return The accessibility text.
7174     *
7175     * @hide
7176     */
7177    public CharSequence getIterableTextForAccessibility() {
7178        return getContentDescription();
7179    }
7180
7181    /**
7182     * Gets whether accessibility selection can be extended.
7183     *
7184     * @return If selection is extensible.
7185     *
7186     * @hide
7187     */
7188    public boolean isAccessibilitySelectionExtendable() {
7189        return false;
7190    }
7191
7192    /**
7193     * @hide
7194     */
7195    public int getAccessibilitySelectionStart() {
7196        return mAccessibilityCursorPosition;
7197    }
7198
7199    /**
7200     * @hide
7201     */
7202    public int getAccessibilitySelectionEnd() {
7203        return getAccessibilitySelectionStart();
7204    }
7205
7206    /**
7207     * @hide
7208     */
7209    public void setAccessibilitySelection(int start, int end) {
7210        if (start ==  end && end == mAccessibilityCursorPosition) {
7211            return;
7212        }
7213        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7214            mAccessibilityCursorPosition = start;
7215        } else {
7216            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7217        }
7218        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7219    }
7220
7221    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7222            int fromIndex, int toIndex) {
7223        if (mParent == null) {
7224            return;
7225        }
7226        AccessibilityEvent event = AccessibilityEvent.obtain(
7227                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7228        onInitializeAccessibilityEvent(event);
7229        onPopulateAccessibilityEvent(event);
7230        event.setFromIndex(fromIndex);
7231        event.setToIndex(toIndex);
7232        event.setAction(action);
7233        event.setMovementGranularity(granularity);
7234        mParent.requestSendAccessibilityEvent(this, event);
7235    }
7236
7237    /**
7238     * @hide
7239     */
7240    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7241        switch (granularity) {
7242            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7243                CharSequence text = getIterableTextForAccessibility();
7244                if (text != null && text.length() > 0) {
7245                    CharacterTextSegmentIterator iterator =
7246                        CharacterTextSegmentIterator.getInstance(
7247                                mContext.getResources().getConfiguration().locale);
7248                    iterator.initialize(text.toString());
7249                    return iterator;
7250                }
7251            } break;
7252            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7253                CharSequence text = getIterableTextForAccessibility();
7254                if (text != null && text.length() > 0) {
7255                    WordTextSegmentIterator iterator =
7256                        WordTextSegmentIterator.getInstance(
7257                                mContext.getResources().getConfiguration().locale);
7258                    iterator.initialize(text.toString());
7259                    return iterator;
7260                }
7261            } break;
7262            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7263                CharSequence text = getIterableTextForAccessibility();
7264                if (text != null && text.length() > 0) {
7265                    ParagraphTextSegmentIterator iterator =
7266                        ParagraphTextSegmentIterator.getInstance();
7267                    iterator.initialize(text.toString());
7268                    return iterator;
7269                }
7270            } break;
7271        }
7272        return null;
7273    }
7274
7275    /**
7276     * @hide
7277     */
7278    public void dispatchStartTemporaryDetach() {
7279        clearAccessibilityFocus();
7280        clearDisplayList();
7281
7282        onStartTemporaryDetach();
7283    }
7284
7285    /**
7286     * This is called when a container is going to temporarily detach a child, with
7287     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7288     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7289     * {@link #onDetachedFromWindow()} when the container is done.
7290     */
7291    public void onStartTemporaryDetach() {
7292        removeUnsetPressCallback();
7293        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7294    }
7295
7296    /**
7297     * @hide
7298     */
7299    public void dispatchFinishTemporaryDetach() {
7300        onFinishTemporaryDetach();
7301    }
7302
7303    /**
7304     * Called after {@link #onStartTemporaryDetach} when the container is done
7305     * changing the view.
7306     */
7307    public void onFinishTemporaryDetach() {
7308    }
7309
7310    /**
7311     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7312     * for this view's window.  Returns null if the view is not currently attached
7313     * to the window.  Normally you will not need to use this directly, but
7314     * just use the standard high-level event callbacks like
7315     * {@link #onKeyDown(int, KeyEvent)}.
7316     */
7317    public KeyEvent.DispatcherState getKeyDispatcherState() {
7318        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7319    }
7320
7321    /**
7322     * Dispatch 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 event The key event to be dispatched.
7329     * @return True if the event was handled, false otherwise.
7330     */
7331    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7332        return onKeyPreIme(event.getKeyCode(), event);
7333    }
7334
7335    /**
7336     * Dispatch a key event to the next view on the focus path. This path runs
7337     * from the top of the view tree down to the currently focused view. If this
7338     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7339     * the next node down the focus path. This method also fires any key
7340     * listeners.
7341     *
7342     * @param event The key event to be dispatched.
7343     * @return True if the event was handled, false otherwise.
7344     */
7345    public boolean dispatchKeyEvent(KeyEvent event) {
7346        if (mInputEventConsistencyVerifier != null) {
7347            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7348        }
7349
7350        // Give any attached key listener a first crack at the event.
7351        //noinspection SimplifiableIfStatement
7352        ListenerInfo li = mListenerInfo;
7353        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7354                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7355            return true;
7356        }
7357
7358        if (event.dispatch(this, mAttachInfo != null
7359                ? mAttachInfo.mKeyDispatchState : null, this)) {
7360            return true;
7361        }
7362
7363        if (mInputEventConsistencyVerifier != null) {
7364            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7365        }
7366        return false;
7367    }
7368
7369    /**
7370     * Dispatches a key shortcut event.
7371     *
7372     * @param event The key event to be dispatched.
7373     * @return True if the event was handled by the view, false otherwise.
7374     */
7375    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7376        return onKeyShortcut(event.getKeyCode(), event);
7377    }
7378
7379    /**
7380     * Pass the touch screen motion event down to the target view, or this
7381     * view if it is the target.
7382     *
7383     * @param event The motion event to be dispatched.
7384     * @return True if the event was handled by the view, false otherwise.
7385     */
7386    public boolean dispatchTouchEvent(MotionEvent event) {
7387        if (mInputEventConsistencyVerifier != null) {
7388            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7389        }
7390
7391        if (onFilterTouchEventForSecurity(event)) {
7392            //noinspection SimplifiableIfStatement
7393            ListenerInfo li = mListenerInfo;
7394            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7395                    && li.mOnTouchListener.onTouch(this, event)) {
7396                return true;
7397            }
7398
7399            if (onTouchEvent(event)) {
7400                return true;
7401            }
7402        }
7403
7404        if (mInputEventConsistencyVerifier != null) {
7405            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7406        }
7407        return false;
7408    }
7409
7410    /**
7411     * Filter the touch event to apply security policies.
7412     *
7413     * @param event The motion event to be filtered.
7414     * @return True if the event should be dispatched, false if the event should be dropped.
7415     *
7416     * @see #getFilterTouchesWhenObscured
7417     */
7418    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7419        //noinspection RedundantIfStatement
7420        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7421                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7422            // Window is obscured, drop this touch.
7423            return false;
7424        }
7425        return true;
7426    }
7427
7428    /**
7429     * Pass a trackball motion event down to the focused view.
7430     *
7431     * @param event The motion event to be dispatched.
7432     * @return True if the event was handled by the view, false otherwise.
7433     */
7434    public boolean dispatchTrackballEvent(MotionEvent event) {
7435        if (mInputEventConsistencyVerifier != null) {
7436            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7437        }
7438
7439        return onTrackballEvent(event);
7440    }
7441
7442    /**
7443     * Dispatch a generic motion event.
7444     * <p>
7445     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7446     * are delivered to the view under the pointer.  All other generic motion events are
7447     * delivered to the focused view.  Hover events are handled specially and are delivered
7448     * to {@link #onHoverEvent(MotionEvent)}.
7449     * </p>
7450     *
7451     * @param event The motion event to be dispatched.
7452     * @return True if the event was handled by the view, false otherwise.
7453     */
7454    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7455        if (mInputEventConsistencyVerifier != null) {
7456            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7457        }
7458
7459        final int source = event.getSource();
7460        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7461            final int action = event.getAction();
7462            if (action == MotionEvent.ACTION_HOVER_ENTER
7463                    || action == MotionEvent.ACTION_HOVER_MOVE
7464                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7465                if (dispatchHoverEvent(event)) {
7466                    return true;
7467                }
7468            } else if (dispatchGenericPointerEvent(event)) {
7469                return true;
7470            }
7471        } else if (dispatchGenericFocusedEvent(event)) {
7472            return true;
7473        }
7474
7475        if (dispatchGenericMotionEventInternal(event)) {
7476            return true;
7477        }
7478
7479        if (mInputEventConsistencyVerifier != null) {
7480            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7481        }
7482        return false;
7483    }
7484
7485    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7486        //noinspection SimplifiableIfStatement
7487        ListenerInfo li = mListenerInfo;
7488        if (li != null && li.mOnGenericMotionListener != null
7489                && (mViewFlags & ENABLED_MASK) == ENABLED
7490                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7491            return true;
7492        }
7493
7494        if (onGenericMotionEvent(event)) {
7495            return true;
7496        }
7497
7498        if (mInputEventConsistencyVerifier != null) {
7499            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7500        }
7501        return false;
7502    }
7503
7504    /**
7505     * Dispatch a hover event.
7506     * <p>
7507     * Do not call this method directly.
7508     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7509     * </p>
7510     *
7511     * @param event The motion event to be dispatched.
7512     * @return True if the event was handled by the view, false otherwise.
7513     */
7514    protected boolean dispatchHoverEvent(MotionEvent event) {
7515        //noinspection SimplifiableIfStatement
7516        ListenerInfo li = mListenerInfo;
7517        if (li != null && li.mOnHoverListener != null
7518                && (mViewFlags & ENABLED_MASK) == ENABLED
7519                && li.mOnHoverListener.onHover(this, event)) {
7520            return true;
7521        }
7522
7523        return onHoverEvent(event);
7524    }
7525
7526    /**
7527     * Returns true if the view has a child to which it has recently sent
7528     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7529     * it does not have a hovered child, then it must be the innermost hovered view.
7530     * @hide
7531     */
7532    protected boolean hasHoveredChild() {
7533        return false;
7534    }
7535
7536    /**
7537     * Dispatch a generic motion event to the view under the first pointer.
7538     * <p>
7539     * Do not call this method directly.
7540     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7541     * </p>
7542     *
7543     * @param event The motion event to be dispatched.
7544     * @return True if the event was handled by the view, false otherwise.
7545     */
7546    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7547        return false;
7548    }
7549
7550    /**
7551     * Dispatch a generic motion event to the currently focused view.
7552     * <p>
7553     * Do not call this method directly.
7554     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7555     * </p>
7556     *
7557     * @param event The motion event to be dispatched.
7558     * @return True if the event was handled by the view, false otherwise.
7559     */
7560    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7561        return false;
7562    }
7563
7564    /**
7565     * Dispatch a pointer event.
7566     * <p>
7567     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7568     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7569     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7570     * and should not be expected to handle other pointing device features.
7571     * </p>
7572     *
7573     * @param event The motion event to be dispatched.
7574     * @return True if the event was handled by the view, false otherwise.
7575     * @hide
7576     */
7577    public final boolean dispatchPointerEvent(MotionEvent event) {
7578        if (event.isTouchEvent()) {
7579            return dispatchTouchEvent(event);
7580        } else {
7581            return dispatchGenericMotionEvent(event);
7582        }
7583    }
7584
7585    /**
7586     * Called when the window containing this view gains or loses window focus.
7587     * ViewGroups should override to route to their children.
7588     *
7589     * @param hasFocus True if the window containing this view now has focus,
7590     *        false otherwise.
7591     */
7592    public void dispatchWindowFocusChanged(boolean hasFocus) {
7593        onWindowFocusChanged(hasFocus);
7594    }
7595
7596    /**
7597     * Called when the window containing this view gains or loses focus.  Note
7598     * that this is separate from view focus: to receive key events, both
7599     * your view and its window must have focus.  If a window is displayed
7600     * on top of yours that takes input focus, then your own window will lose
7601     * focus but the view focus will remain unchanged.
7602     *
7603     * @param hasWindowFocus True if the window containing this view now has
7604     *        focus, false otherwise.
7605     */
7606    public void onWindowFocusChanged(boolean hasWindowFocus) {
7607        InputMethodManager imm = InputMethodManager.peekInstance();
7608        if (!hasWindowFocus) {
7609            if (isPressed()) {
7610                setPressed(false);
7611            }
7612            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7613                imm.focusOut(this);
7614            }
7615            removeLongPressCallback();
7616            removeTapCallback();
7617            onFocusLost();
7618        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7619            imm.focusIn(this);
7620        }
7621        refreshDrawableState();
7622    }
7623
7624    /**
7625     * Returns true if this view is in a window that currently has window focus.
7626     * Note that this is not the same as the view itself having focus.
7627     *
7628     * @return True if this view is in a window that currently has window focus.
7629     */
7630    public boolean hasWindowFocus() {
7631        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7632    }
7633
7634    /**
7635     * Dispatch a view visibility change down the view hierarchy.
7636     * ViewGroups should override to route to their children.
7637     * @param changedView The view whose visibility changed. Could be 'this' or
7638     * an ancestor view.
7639     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7640     * {@link #INVISIBLE} or {@link #GONE}.
7641     */
7642    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7643        onVisibilityChanged(changedView, visibility);
7644    }
7645
7646    /**
7647     * Called when the visibility of the view or an ancestor of the view is changed.
7648     * @param changedView The view whose visibility changed. Could be 'this' or
7649     * an ancestor view.
7650     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7651     * {@link #INVISIBLE} or {@link #GONE}.
7652     */
7653    protected void onVisibilityChanged(View changedView, int visibility) {
7654        if (visibility == VISIBLE) {
7655            if (mAttachInfo != null) {
7656                initialAwakenScrollBars();
7657            } else {
7658                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7659            }
7660        }
7661    }
7662
7663    /**
7664     * Dispatch a hint about whether this view is displayed. For instance, when
7665     * a View moves out of the screen, it might receives a display hint indicating
7666     * the view is not displayed. Applications should not <em>rely</em> on this hint
7667     * as there is no guarantee that they will receive one.
7668     *
7669     * @param hint A hint about whether or not this view is displayed:
7670     * {@link #VISIBLE} or {@link #INVISIBLE}.
7671     */
7672    public void dispatchDisplayHint(int hint) {
7673        onDisplayHint(hint);
7674    }
7675
7676    /**
7677     * Gives this view a hint about whether is displayed or not. For instance, when
7678     * a View moves out of the screen, it might receives a display hint indicating
7679     * the view is not displayed. Applications should not <em>rely</em> on this hint
7680     * as there is no guarantee that they will receive one.
7681     *
7682     * @param hint A hint about whether or not this view is displayed:
7683     * {@link #VISIBLE} or {@link #INVISIBLE}.
7684     */
7685    protected void onDisplayHint(int hint) {
7686    }
7687
7688    /**
7689     * Dispatch a window visibility change down the view hierarchy.
7690     * ViewGroups should override to route to their children.
7691     *
7692     * @param visibility The new visibility of the window.
7693     *
7694     * @see #onWindowVisibilityChanged(int)
7695     */
7696    public void dispatchWindowVisibilityChanged(int visibility) {
7697        onWindowVisibilityChanged(visibility);
7698    }
7699
7700    /**
7701     * Called when the window containing has change its visibility
7702     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7703     * that this tells you whether or not your window is being made visible
7704     * to the window manager; this does <em>not</em> tell you whether or not
7705     * your window is obscured by other windows on the screen, even if it
7706     * is itself visible.
7707     *
7708     * @param visibility The new visibility of the window.
7709     */
7710    protected void onWindowVisibilityChanged(int visibility) {
7711        if (visibility == VISIBLE) {
7712            initialAwakenScrollBars();
7713        }
7714    }
7715
7716    /**
7717     * Returns the current visibility of the window this view is attached to
7718     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7719     *
7720     * @return Returns the current visibility of the view's window.
7721     */
7722    public int getWindowVisibility() {
7723        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7724    }
7725
7726    /**
7727     * Retrieve the overall visible display size in which the window this view is
7728     * attached to has been positioned in.  This takes into account screen
7729     * decorations above the window, for both cases where the window itself
7730     * is being position inside of them or the window is being placed under
7731     * then and covered insets are used for the window to position its content
7732     * inside.  In effect, this tells you the available area where content can
7733     * be placed and remain visible to users.
7734     *
7735     * <p>This function requires an IPC back to the window manager to retrieve
7736     * the requested information, so should not be used in performance critical
7737     * code like drawing.
7738     *
7739     * @param outRect Filled in with the visible display frame.  If the view
7740     * is not attached to a window, this is simply the raw display size.
7741     */
7742    public void getWindowVisibleDisplayFrame(Rect outRect) {
7743        if (mAttachInfo != null) {
7744            try {
7745                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7746            } catch (RemoteException e) {
7747                return;
7748            }
7749            // XXX This is really broken, and probably all needs to be done
7750            // in the window manager, and we need to know more about whether
7751            // we want the area behind or in front of the IME.
7752            final Rect insets = mAttachInfo.mVisibleInsets;
7753            outRect.left += insets.left;
7754            outRect.top += insets.top;
7755            outRect.right -= insets.right;
7756            outRect.bottom -= insets.bottom;
7757            return;
7758        }
7759        // The view is not attached to a display so we don't have a context.
7760        // Make a best guess about the display size.
7761        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7762        d.getRectSize(outRect);
7763    }
7764
7765    /**
7766     * Dispatch a notification about a resource configuration change down
7767     * the view hierarchy.
7768     * ViewGroups should override to route to their children.
7769     *
7770     * @param newConfig The new resource configuration.
7771     *
7772     * @see #onConfigurationChanged(android.content.res.Configuration)
7773     */
7774    public void dispatchConfigurationChanged(Configuration newConfig) {
7775        onConfigurationChanged(newConfig);
7776    }
7777
7778    /**
7779     * Called when the current configuration of the resources being used
7780     * by the application have changed.  You can use this to decide when
7781     * to reload resources that can changed based on orientation and other
7782     * configuration characterstics.  You only need to use this if you are
7783     * not relying on the normal {@link android.app.Activity} mechanism of
7784     * recreating the activity instance upon a configuration change.
7785     *
7786     * @param newConfig The new resource configuration.
7787     */
7788    protected void onConfigurationChanged(Configuration newConfig) {
7789    }
7790
7791    /**
7792     * Private function to aggregate all per-view attributes in to the view
7793     * root.
7794     */
7795    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7796        performCollectViewAttributes(attachInfo, visibility);
7797    }
7798
7799    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7800        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7801            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7802                attachInfo.mKeepScreenOn = true;
7803            }
7804            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7805            ListenerInfo li = mListenerInfo;
7806            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7807                attachInfo.mHasSystemUiListeners = true;
7808            }
7809        }
7810    }
7811
7812    void needGlobalAttributesUpdate(boolean force) {
7813        final AttachInfo ai = mAttachInfo;
7814        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7815            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7816                    || ai.mHasSystemUiListeners) {
7817                ai.mRecomputeGlobalAttributes = true;
7818            }
7819        }
7820    }
7821
7822    /**
7823     * Returns whether the device is currently in touch mode.  Touch mode is entered
7824     * once the user begins interacting with the device by touch, and affects various
7825     * things like whether focus is always visible to the user.
7826     *
7827     * @return Whether the device is in touch mode.
7828     */
7829    @ViewDebug.ExportedProperty
7830    public boolean isInTouchMode() {
7831        if (mAttachInfo != null) {
7832            return mAttachInfo.mInTouchMode;
7833        } else {
7834            return ViewRootImpl.isInTouchMode();
7835        }
7836    }
7837
7838    /**
7839     * Returns the context the view is running in, through which it can
7840     * access the current theme, resources, etc.
7841     *
7842     * @return The view's Context.
7843     */
7844    @ViewDebug.CapturedViewProperty
7845    public final Context getContext() {
7846        return mContext;
7847    }
7848
7849    /**
7850     * Handle a key event before it is processed by any input method
7851     * associated with the view hierarchy.  This can be used to intercept
7852     * key events in special situations before the IME consumes them; a
7853     * typical example would be handling the BACK key to update the application's
7854     * UI instead of allowing the IME to see it and close itself.
7855     *
7856     * @param keyCode The value in event.getKeyCode().
7857     * @param event Description of the key event.
7858     * @return If you handled the event, return true. If you want to allow the
7859     *         event to be handled by the next receiver, return false.
7860     */
7861    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7862        return false;
7863    }
7864
7865    /**
7866     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7867     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7868     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7869     * is released, if the view is enabled and clickable.
7870     *
7871     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7872     * although some may elect to do so in some situations. Do not rely on this to
7873     * catch software key presses.
7874     *
7875     * @param keyCode A key code that represents the button pressed, from
7876     *                {@link android.view.KeyEvent}.
7877     * @param event   The KeyEvent object that defines the button action.
7878     */
7879    public boolean onKeyDown(int keyCode, KeyEvent event) {
7880        boolean result = false;
7881
7882        switch (keyCode) {
7883            case KeyEvent.KEYCODE_DPAD_CENTER:
7884            case KeyEvent.KEYCODE_ENTER: {
7885                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7886                    return true;
7887                }
7888                // Long clickable items don't necessarily have to be clickable
7889                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7890                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7891                        (event.getRepeatCount() == 0)) {
7892                    setPressed(true);
7893                    checkForLongClick(0);
7894                    return true;
7895                }
7896                break;
7897            }
7898        }
7899        return result;
7900    }
7901
7902    /**
7903     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7904     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7905     * the event).
7906     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7907     * although some may elect to do so in some situations. Do not rely on this to
7908     * catch software key presses.
7909     */
7910    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7911        return false;
7912    }
7913
7914    /**
7915     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7916     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7917     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7918     * {@link KeyEvent#KEYCODE_ENTER} is released.
7919     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7920     * although some may elect to do so in some situations. Do not rely on this to
7921     * catch software key presses.
7922     *
7923     * @param keyCode A key code that represents the button pressed, from
7924     *                {@link android.view.KeyEvent}.
7925     * @param event   The KeyEvent object that defines the button action.
7926     */
7927    public boolean onKeyUp(int keyCode, KeyEvent event) {
7928        boolean result = false;
7929
7930        switch (keyCode) {
7931            case KeyEvent.KEYCODE_DPAD_CENTER:
7932            case KeyEvent.KEYCODE_ENTER: {
7933                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7934                    return true;
7935                }
7936                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7937                    setPressed(false);
7938
7939                    if (!mHasPerformedLongPress) {
7940                        // This is a tap, so remove the longpress check
7941                        removeLongPressCallback();
7942
7943                        result = performClick();
7944                    }
7945                }
7946                break;
7947            }
7948        }
7949        return result;
7950    }
7951
7952    /**
7953     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7954     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7955     * the event).
7956     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7957     * although some may elect to do so in some situations. Do not rely on this to
7958     * catch software key presses.
7959     *
7960     * @param keyCode     A key code that represents the button pressed, from
7961     *                    {@link android.view.KeyEvent}.
7962     * @param repeatCount The number of times the action was made.
7963     * @param event       The KeyEvent object that defines the button action.
7964     */
7965    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7966        return false;
7967    }
7968
7969    /**
7970     * Called on the focused view when a key shortcut event is not handled.
7971     * Override this method to implement local key shortcuts for the View.
7972     * Key shortcuts can also be implemented by setting the
7973     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7974     *
7975     * @param keyCode The value in event.getKeyCode().
7976     * @param event Description of the key event.
7977     * @return If you handled the event, return true. If you want to allow the
7978     *         event to be handled by the next receiver, return false.
7979     */
7980    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7981        return false;
7982    }
7983
7984    /**
7985     * Check whether the called view is a text editor, in which case it
7986     * would make sense to automatically display a soft input window for
7987     * it.  Subclasses should override this if they implement
7988     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7989     * a call on that method would return a non-null InputConnection, and
7990     * they are really a first-class editor that the user would normally
7991     * start typing on when the go into a window containing your view.
7992     *
7993     * <p>The default implementation always returns false.  This does
7994     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7995     * will not be called or the user can not otherwise perform edits on your
7996     * view; it is just a hint to the system that this is not the primary
7997     * purpose of this view.
7998     *
7999     * @return Returns true if this view is a text editor, else false.
8000     */
8001    public boolean onCheckIsTextEditor() {
8002        return false;
8003    }
8004
8005    /**
8006     * Create a new InputConnection for an InputMethod to interact
8007     * with the view.  The default implementation returns null, since it doesn't
8008     * support input methods.  You can override this to implement such support.
8009     * This is only needed for views that take focus and text input.
8010     *
8011     * <p>When implementing this, you probably also want to implement
8012     * {@link #onCheckIsTextEditor()} to indicate you will return a
8013     * non-null InputConnection.
8014     *
8015     * @param outAttrs Fill in with attribute information about the connection.
8016     */
8017    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8018        return null;
8019    }
8020
8021    /**
8022     * Called by the {@link android.view.inputmethod.InputMethodManager}
8023     * when a view who is not the current
8024     * input connection target is trying to make a call on the manager.  The
8025     * default implementation returns false; you can override this to return
8026     * true for certain views if you are performing InputConnection proxying
8027     * to them.
8028     * @param view The View that is making the InputMethodManager call.
8029     * @return Return true to allow the call, false to reject.
8030     */
8031    public boolean checkInputConnectionProxy(View view) {
8032        return false;
8033    }
8034
8035    /**
8036     * Show the context menu for this view. It is not safe to hold on to the
8037     * menu after returning from this method.
8038     *
8039     * You should normally not overload this method. Overload
8040     * {@link #onCreateContextMenu(ContextMenu)} or define an
8041     * {@link OnCreateContextMenuListener} to add items to the context menu.
8042     *
8043     * @param menu The context menu to populate
8044     */
8045    public void createContextMenu(ContextMenu menu) {
8046        ContextMenuInfo menuInfo = getContextMenuInfo();
8047
8048        // Sets the current menu info so all items added to menu will have
8049        // my extra info set.
8050        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8051
8052        onCreateContextMenu(menu);
8053        ListenerInfo li = mListenerInfo;
8054        if (li != null && li.mOnCreateContextMenuListener != null) {
8055            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8056        }
8057
8058        // Clear the extra information so subsequent items that aren't mine don't
8059        // have my extra info.
8060        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8061
8062        if (mParent != null) {
8063            mParent.createContextMenu(menu);
8064        }
8065    }
8066
8067    /**
8068     * Views should implement this if they have extra information to associate
8069     * with the context menu. The return result is supplied as a parameter to
8070     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8071     * callback.
8072     *
8073     * @return Extra information about the item for which the context menu
8074     *         should be shown. This information will vary across different
8075     *         subclasses of View.
8076     */
8077    protected ContextMenuInfo getContextMenuInfo() {
8078        return null;
8079    }
8080
8081    /**
8082     * Views should implement this if the view itself is going to add items to
8083     * the context menu.
8084     *
8085     * @param menu the context menu to populate
8086     */
8087    protected void onCreateContextMenu(ContextMenu menu) {
8088    }
8089
8090    /**
8091     * Implement this method to handle trackball motion events.  The
8092     * <em>relative</em> movement of the trackball since the last event
8093     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8094     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8095     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8096     * they will often be fractional values, representing the more fine-grained
8097     * movement information available from a trackball).
8098     *
8099     * @param event The motion event.
8100     * @return True if the event was handled, false otherwise.
8101     */
8102    public boolean onTrackballEvent(MotionEvent event) {
8103        return false;
8104    }
8105
8106    /**
8107     * Implement this method to handle generic motion events.
8108     * <p>
8109     * Generic motion events describe joystick movements, mouse hovers, track pad
8110     * touches, scroll wheel movements and other input events.  The
8111     * {@link MotionEvent#getSource() source} of the motion event specifies
8112     * the class of input that was received.  Implementations of this method
8113     * must examine the bits in the source before processing the event.
8114     * The following code example shows how this is done.
8115     * </p><p>
8116     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8117     * are delivered to the view under the pointer.  All other generic motion events are
8118     * delivered to the focused view.
8119     * </p>
8120     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8121     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
8122     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8123     *             // process the joystick movement...
8124     *             return true;
8125     *         }
8126     *     }
8127     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
8128     *         switch (event.getAction()) {
8129     *             case MotionEvent.ACTION_HOVER_MOVE:
8130     *                 // process the mouse hover movement...
8131     *                 return true;
8132     *             case MotionEvent.ACTION_SCROLL:
8133     *                 // process the scroll wheel movement...
8134     *                 return true;
8135     *         }
8136     *     }
8137     *     return super.onGenericMotionEvent(event);
8138     * }</pre>
8139     *
8140     * @param event The generic motion event being processed.
8141     * @return True if the event was handled, false otherwise.
8142     */
8143    public boolean onGenericMotionEvent(MotionEvent event) {
8144        return false;
8145    }
8146
8147    /**
8148     * Implement this method to handle hover events.
8149     * <p>
8150     * This method is called whenever a pointer is hovering into, over, or out of the
8151     * bounds of a view and the view is not currently being touched.
8152     * Hover events are represented as pointer events with action
8153     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8154     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8155     * </p>
8156     * <ul>
8157     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8158     * when the pointer enters the bounds of the view.</li>
8159     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8160     * when the pointer has already entered the bounds of the view and has moved.</li>
8161     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8162     * when the pointer has exited the bounds of the view or when the pointer is
8163     * about to go down due to a button click, tap, or similar user action that
8164     * causes the view to be touched.</li>
8165     * </ul>
8166     * <p>
8167     * The view should implement this method to return true to indicate that it is
8168     * handling the hover event, such as by changing its drawable state.
8169     * </p><p>
8170     * The default implementation calls {@link #setHovered} to update the hovered state
8171     * of the view when a hover enter or hover exit event is received, if the view
8172     * is enabled and is clickable.  The default implementation also sends hover
8173     * accessibility events.
8174     * </p>
8175     *
8176     * @param event The motion event that describes the hover.
8177     * @return True if the view handled the hover event.
8178     *
8179     * @see #isHovered
8180     * @see #setHovered
8181     * @see #onHoverChanged
8182     */
8183    public boolean onHoverEvent(MotionEvent event) {
8184        // The root view may receive hover (or touch) events that are outside the bounds of
8185        // the window.  This code ensures that we only send accessibility events for
8186        // hovers that are actually within the bounds of the root view.
8187        final int action = event.getActionMasked();
8188        if (!mSendingHoverAccessibilityEvents) {
8189            if ((action == MotionEvent.ACTION_HOVER_ENTER
8190                    || action == MotionEvent.ACTION_HOVER_MOVE)
8191                    && !hasHoveredChild()
8192                    && pointInView(event.getX(), event.getY())) {
8193                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8194                mSendingHoverAccessibilityEvents = true;
8195            }
8196        } else {
8197            if (action == MotionEvent.ACTION_HOVER_EXIT
8198                    || (action == MotionEvent.ACTION_MOVE
8199                            && !pointInView(event.getX(), event.getY()))) {
8200                mSendingHoverAccessibilityEvents = false;
8201                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8202                // If the window does not have input focus we take away accessibility
8203                // focus as soon as the user stop hovering over the view.
8204                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8205                    getViewRootImpl().setAccessibilityFocus(null, null);
8206                }
8207            }
8208        }
8209
8210        if (isHoverable()) {
8211            switch (action) {
8212                case MotionEvent.ACTION_HOVER_ENTER:
8213                    setHovered(true);
8214                    break;
8215                case MotionEvent.ACTION_HOVER_EXIT:
8216                    setHovered(false);
8217                    break;
8218            }
8219
8220            // Dispatch the event to onGenericMotionEvent before returning true.
8221            // This is to provide compatibility with existing applications that
8222            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8223            // break because of the new default handling for hoverable views
8224            // in onHoverEvent.
8225            // Note that onGenericMotionEvent will be called by default when
8226            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8227            return dispatchGenericMotionEventInternal(event);
8228        }
8229
8230        return false;
8231    }
8232
8233    /**
8234     * Returns true if the view should handle {@link #onHoverEvent}
8235     * by calling {@link #setHovered} to change its hovered state.
8236     *
8237     * @return True if the view is hoverable.
8238     */
8239    private boolean isHoverable() {
8240        final int viewFlags = mViewFlags;
8241        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8242            return false;
8243        }
8244
8245        return (viewFlags & CLICKABLE) == CLICKABLE
8246                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8247    }
8248
8249    /**
8250     * Returns true if the view is currently hovered.
8251     *
8252     * @return True if the view is currently hovered.
8253     *
8254     * @see #setHovered
8255     * @see #onHoverChanged
8256     */
8257    @ViewDebug.ExportedProperty
8258    public boolean isHovered() {
8259        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8260    }
8261
8262    /**
8263     * Sets whether the view is currently hovered.
8264     * <p>
8265     * Calling this method also changes the drawable state of the view.  This
8266     * enables the view to react to hover by using different drawable resources
8267     * to change its appearance.
8268     * </p><p>
8269     * The {@link #onHoverChanged} method is called when the hovered state changes.
8270     * </p>
8271     *
8272     * @param hovered True if the view is hovered.
8273     *
8274     * @see #isHovered
8275     * @see #onHoverChanged
8276     */
8277    public void setHovered(boolean hovered) {
8278        if (hovered) {
8279            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8280                mPrivateFlags |= PFLAG_HOVERED;
8281                refreshDrawableState();
8282                onHoverChanged(true);
8283            }
8284        } else {
8285            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8286                mPrivateFlags &= ~PFLAG_HOVERED;
8287                refreshDrawableState();
8288                onHoverChanged(false);
8289            }
8290        }
8291    }
8292
8293    /**
8294     * Implement this method to handle hover state changes.
8295     * <p>
8296     * This method is called whenever the hover state changes as a result of a
8297     * call to {@link #setHovered}.
8298     * </p>
8299     *
8300     * @param hovered The current hover state, as returned by {@link #isHovered}.
8301     *
8302     * @see #isHovered
8303     * @see #setHovered
8304     */
8305    public void onHoverChanged(boolean hovered) {
8306    }
8307
8308    /**
8309     * Implement this method to handle touch screen motion events.
8310     *
8311     * @param event The motion event.
8312     * @return True if the event was handled, false otherwise.
8313     */
8314    public boolean onTouchEvent(MotionEvent event) {
8315        final int viewFlags = mViewFlags;
8316
8317        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8318            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8319                setPressed(false);
8320            }
8321            // A disabled view that is clickable still consumes the touch
8322            // events, it just doesn't respond to them.
8323            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8324                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8325        }
8326
8327        if (mTouchDelegate != null) {
8328            if (mTouchDelegate.onTouchEvent(event)) {
8329                return true;
8330            }
8331        }
8332
8333        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8334                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8335            switch (event.getAction()) {
8336                case MotionEvent.ACTION_UP:
8337                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8338                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8339                        // take focus if we don't have it already and we should in
8340                        // touch mode.
8341                        boolean focusTaken = false;
8342                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8343                            focusTaken = requestFocus();
8344                        }
8345
8346                        if (prepressed) {
8347                            // The button is being released before we actually
8348                            // showed it as pressed.  Make it show the pressed
8349                            // state now (before scheduling the click) to ensure
8350                            // the user sees it.
8351                            setPressed(true);
8352                       }
8353
8354                        if (!mHasPerformedLongPress) {
8355                            // This is a tap, so remove the longpress check
8356                            removeLongPressCallback();
8357
8358                            // Only perform take click actions if we were in the pressed state
8359                            if (!focusTaken) {
8360                                // Use a Runnable and post this rather than calling
8361                                // performClick directly. This lets other visual state
8362                                // of the view update before click actions start.
8363                                if (mPerformClick == null) {
8364                                    mPerformClick = new PerformClick();
8365                                }
8366                                if (!post(mPerformClick)) {
8367                                    performClick();
8368                                }
8369                            }
8370                        }
8371
8372                        if (mUnsetPressedState == null) {
8373                            mUnsetPressedState = new UnsetPressedState();
8374                        }
8375
8376                        if (prepressed) {
8377                            postDelayed(mUnsetPressedState,
8378                                    ViewConfiguration.getPressedStateDuration());
8379                        } else if (!post(mUnsetPressedState)) {
8380                            // If the post failed, unpress right now
8381                            mUnsetPressedState.run();
8382                        }
8383                        removeTapCallback();
8384                    }
8385                    break;
8386
8387                case MotionEvent.ACTION_DOWN:
8388                    mHasPerformedLongPress = false;
8389
8390                    if (performButtonActionOnTouchDown(event)) {
8391                        break;
8392                    }
8393
8394                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8395                    boolean isInScrollingContainer = isInScrollingContainer();
8396
8397                    // For views inside a scrolling container, delay the pressed feedback for
8398                    // a short period in case this is a scroll.
8399                    if (isInScrollingContainer) {
8400                        mPrivateFlags |= PFLAG_PREPRESSED;
8401                        if (mPendingCheckForTap == null) {
8402                            mPendingCheckForTap = new CheckForTap();
8403                        }
8404                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8405                    } else {
8406                        // Not inside a scrolling container, so show the feedback right away
8407                        setPressed(true);
8408                        checkForLongClick(0);
8409                    }
8410                    break;
8411
8412                case MotionEvent.ACTION_CANCEL:
8413                    setPressed(false);
8414                    removeTapCallback();
8415                    removeLongPressCallback();
8416                    break;
8417
8418                case MotionEvent.ACTION_MOVE:
8419                    final int x = (int) event.getX();
8420                    final int y = (int) event.getY();
8421
8422                    // Be lenient about moving outside of buttons
8423                    if (!pointInView(x, y, mTouchSlop)) {
8424                        // Outside button
8425                        removeTapCallback();
8426                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8427                            // Remove any future long press/tap checks
8428                            removeLongPressCallback();
8429
8430                            setPressed(false);
8431                        }
8432                    }
8433                    break;
8434            }
8435            return true;
8436        }
8437
8438        return false;
8439    }
8440
8441    /**
8442     * @hide
8443     */
8444    public boolean isInScrollingContainer() {
8445        ViewParent p = getParent();
8446        while (p != null && p instanceof ViewGroup) {
8447            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8448                return true;
8449            }
8450            p = p.getParent();
8451        }
8452        return false;
8453    }
8454
8455    /**
8456     * Remove the longpress detection timer.
8457     */
8458    private void removeLongPressCallback() {
8459        if (mPendingCheckForLongPress != null) {
8460          removeCallbacks(mPendingCheckForLongPress);
8461        }
8462    }
8463
8464    /**
8465     * Remove the pending click action
8466     */
8467    private void removePerformClickCallback() {
8468        if (mPerformClick != null) {
8469            removeCallbacks(mPerformClick);
8470        }
8471    }
8472
8473    /**
8474     * Remove the prepress detection timer.
8475     */
8476    private void removeUnsetPressCallback() {
8477        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8478            setPressed(false);
8479            removeCallbacks(mUnsetPressedState);
8480        }
8481    }
8482
8483    /**
8484     * Remove the tap detection timer.
8485     */
8486    private void removeTapCallback() {
8487        if (mPendingCheckForTap != null) {
8488            mPrivateFlags &= ~PFLAG_PREPRESSED;
8489            removeCallbacks(mPendingCheckForTap);
8490        }
8491    }
8492
8493    /**
8494     * Cancels a pending long press.  Your subclass can use this if you
8495     * want the context menu to come up if the user presses and holds
8496     * at the same place, but you don't want it to come up if they press
8497     * and then move around enough to cause scrolling.
8498     */
8499    public void cancelLongPress() {
8500        removeLongPressCallback();
8501
8502        /*
8503         * The prepressed state handled by the tap callback is a display
8504         * construct, but the tap callback will post a long press callback
8505         * less its own timeout. Remove it here.
8506         */
8507        removeTapCallback();
8508    }
8509
8510    /**
8511     * Remove the pending callback for sending a
8512     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8513     */
8514    private void removeSendViewScrolledAccessibilityEventCallback() {
8515        if (mSendViewScrolledAccessibilityEvent != null) {
8516            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8517            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8518        }
8519    }
8520
8521    /**
8522     * Sets the TouchDelegate for this View.
8523     */
8524    public void setTouchDelegate(TouchDelegate delegate) {
8525        mTouchDelegate = delegate;
8526    }
8527
8528    /**
8529     * Gets the TouchDelegate for this View.
8530     */
8531    public TouchDelegate getTouchDelegate() {
8532        return mTouchDelegate;
8533    }
8534
8535    /**
8536     * Set flags controlling behavior of this view.
8537     *
8538     * @param flags Constant indicating the value which should be set
8539     * @param mask Constant indicating the bit range that should be changed
8540     */
8541    void setFlags(int flags, int mask) {
8542        int old = mViewFlags;
8543        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8544
8545        int changed = mViewFlags ^ old;
8546        if (changed == 0) {
8547            return;
8548        }
8549        int privateFlags = mPrivateFlags;
8550
8551        /* Check if the FOCUSABLE bit has changed */
8552        if (((changed & FOCUSABLE_MASK) != 0) &&
8553                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8554            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8555                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8556                /* Give up focus if we are no longer focusable */
8557                clearFocus();
8558            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8559                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8560                /*
8561                 * Tell the view system that we are now available to take focus
8562                 * if no one else already has it.
8563                 */
8564                if (mParent != null) mParent.focusableViewAvailable(this);
8565            }
8566            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8567                notifyAccessibilityStateChanged();
8568            }
8569        }
8570
8571        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8572            if ((changed & VISIBILITY_MASK) != 0) {
8573                /*
8574                 * If this view is becoming visible, invalidate it in case it changed while
8575                 * it was not visible. Marking it drawn ensures that the invalidation will
8576                 * go through.
8577                 */
8578                mPrivateFlags |= PFLAG_DRAWN;
8579                invalidate(true);
8580
8581                needGlobalAttributesUpdate(true);
8582
8583                // a view becoming visible is worth notifying the parent
8584                // about in case nothing has focus.  even if this specific view
8585                // isn't focusable, it may contain something that is, so let
8586                // the root view try to give this focus if nothing else does.
8587                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8588                    mParent.focusableViewAvailable(this);
8589                }
8590            }
8591        }
8592
8593        /* Check if the GONE bit has changed */
8594        if ((changed & GONE) != 0) {
8595            needGlobalAttributesUpdate(false);
8596            requestLayout();
8597
8598            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8599                if (hasFocus()) clearFocus();
8600                clearAccessibilityFocus();
8601                destroyDrawingCache();
8602                if (mParent instanceof View) {
8603                    // GONE views noop invalidation, so invalidate the parent
8604                    ((View) mParent).invalidate(true);
8605                }
8606                // Mark the view drawn to ensure that it gets invalidated properly the next
8607                // time it is visible and gets invalidated
8608                mPrivateFlags |= PFLAG_DRAWN;
8609            }
8610            if (mAttachInfo != null) {
8611                mAttachInfo.mViewVisibilityChanged = true;
8612            }
8613        }
8614
8615        /* Check if the VISIBLE bit has changed */
8616        if ((changed & INVISIBLE) != 0) {
8617            needGlobalAttributesUpdate(false);
8618            /*
8619             * If this view is becoming invisible, set the DRAWN flag so that
8620             * the next invalidate() will not be skipped.
8621             */
8622            mPrivateFlags |= PFLAG_DRAWN;
8623
8624            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8625                // root view becoming invisible shouldn't clear focus and accessibility focus
8626                if (getRootView() != this) {
8627                    clearFocus();
8628                    clearAccessibilityFocus();
8629                }
8630            }
8631            if (mAttachInfo != null) {
8632                mAttachInfo.mViewVisibilityChanged = true;
8633            }
8634        }
8635
8636        if ((changed & VISIBILITY_MASK) != 0) {
8637            if (mParent instanceof ViewGroup) {
8638                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8639                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8640                ((View) mParent).invalidate(true);
8641            } else if (mParent != null) {
8642                mParent.invalidateChild(this, null);
8643            }
8644            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8645        }
8646
8647        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8648            destroyDrawingCache();
8649        }
8650
8651        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8652            destroyDrawingCache();
8653            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8654            invalidateParentCaches();
8655        }
8656
8657        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8658            destroyDrawingCache();
8659            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8660        }
8661
8662        if ((changed & DRAW_MASK) != 0) {
8663            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8664                if (mBackground != null) {
8665                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8666                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8667                } else {
8668                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8669                }
8670            } else {
8671                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8672            }
8673            requestLayout();
8674            invalidate(true);
8675        }
8676
8677        if ((changed & KEEP_SCREEN_ON) != 0) {
8678            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8679                mParent.recomputeViewAttributes(this);
8680            }
8681        }
8682
8683        if (AccessibilityManager.getInstance(mContext).isEnabled()
8684                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8685                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8686            notifyAccessibilityStateChanged();
8687        }
8688    }
8689
8690    /**
8691     * Change the view's z order in the tree, so it's on top of other sibling
8692     * views
8693     */
8694    public void bringToFront() {
8695        if (mParent != null) {
8696            mParent.bringChildToFront(this);
8697        }
8698    }
8699
8700    /**
8701     * This is called in response to an internal scroll in this view (i.e., the
8702     * view scrolled its own contents). This is typically as a result of
8703     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8704     * called.
8705     *
8706     * @param l Current horizontal scroll origin.
8707     * @param t Current vertical scroll origin.
8708     * @param oldl Previous horizontal scroll origin.
8709     * @param oldt Previous vertical scroll origin.
8710     */
8711    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8712        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8713            postSendViewScrolledAccessibilityEventCallback();
8714        }
8715
8716        mBackgroundSizeChanged = true;
8717
8718        final AttachInfo ai = mAttachInfo;
8719        if (ai != null) {
8720            ai.mViewScrollChanged = true;
8721        }
8722    }
8723
8724    /**
8725     * Interface definition for a callback to be invoked when the layout bounds of a view
8726     * changes due to layout processing.
8727     */
8728    public interface OnLayoutChangeListener {
8729        /**
8730         * Called when the focus state of a view has changed.
8731         *
8732         * @param v The view whose state has changed.
8733         * @param left The new value of the view's left property.
8734         * @param top The new value of the view's top property.
8735         * @param right The new value of the view's right property.
8736         * @param bottom The new value of the view's bottom property.
8737         * @param oldLeft The previous value of the view's left property.
8738         * @param oldTop The previous value of the view's top property.
8739         * @param oldRight The previous value of the view's right property.
8740         * @param oldBottom The previous value of the view's bottom property.
8741         */
8742        void onLayoutChange(View v, int left, int top, int right, int bottom,
8743            int oldLeft, int oldTop, int oldRight, int oldBottom);
8744    }
8745
8746    /**
8747     * This is called during layout when the size of this view has changed. If
8748     * you were just added to the view hierarchy, you're called with the old
8749     * values of 0.
8750     *
8751     * @param w Current width of this view.
8752     * @param h Current height of this view.
8753     * @param oldw Old width of this view.
8754     * @param oldh Old height of this view.
8755     */
8756    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8757    }
8758
8759    /**
8760     * Called by draw to draw the child views. This may be overridden
8761     * by derived classes to gain control just before its children are drawn
8762     * (but after its own view has been drawn).
8763     * @param canvas the canvas on which to draw the view
8764     */
8765    protected void dispatchDraw(Canvas canvas) {
8766
8767    }
8768
8769    /**
8770     * Gets the parent of this view. Note that the parent is a
8771     * ViewParent and not necessarily a View.
8772     *
8773     * @return Parent of this view.
8774     */
8775    public final ViewParent getParent() {
8776        return mParent;
8777    }
8778
8779    /**
8780     * Set the horizontal scrolled position of your view. This will cause a call to
8781     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8782     * invalidated.
8783     * @param value the x position to scroll to
8784     */
8785    public void setScrollX(int value) {
8786        scrollTo(value, mScrollY);
8787    }
8788
8789    /**
8790     * Set the vertical scrolled position of your view. This will cause a call to
8791     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8792     * invalidated.
8793     * @param value the y position to scroll to
8794     */
8795    public void setScrollY(int value) {
8796        scrollTo(mScrollX, value);
8797    }
8798
8799    /**
8800     * Return the scrolled left position of this view. This is the left edge of
8801     * the displayed part of your view. You do not need to draw any pixels
8802     * farther left, since those are outside of the frame of your view on
8803     * screen.
8804     *
8805     * @return The left edge of the displayed part of your view, in pixels.
8806     */
8807    public final int getScrollX() {
8808        return mScrollX;
8809    }
8810
8811    /**
8812     * Return the scrolled top position of this view. This is the top edge of
8813     * the displayed part of your view. You do not need to draw any pixels above
8814     * it, since those are outside of the frame of your view on screen.
8815     *
8816     * @return The top edge of the displayed part of your view, in pixels.
8817     */
8818    public final int getScrollY() {
8819        return mScrollY;
8820    }
8821
8822    /**
8823     * Return the width of the your view.
8824     *
8825     * @return The width of your view, in pixels.
8826     */
8827    @ViewDebug.ExportedProperty(category = "layout")
8828    public final int getWidth() {
8829        return mRight - mLeft;
8830    }
8831
8832    /**
8833     * Return the height of your view.
8834     *
8835     * @return The height of your view, in pixels.
8836     */
8837    @ViewDebug.ExportedProperty(category = "layout")
8838    public final int getHeight() {
8839        return mBottom - mTop;
8840    }
8841
8842    /**
8843     * Return the visible drawing bounds of your view. Fills in the output
8844     * rectangle with the values from getScrollX(), getScrollY(),
8845     * getWidth(), and getHeight(). These bounds do not account for any
8846     * transformation properties currently set on the view, such as
8847     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8848     *
8849     * @param outRect The (scrolled) drawing bounds of the view.
8850     */
8851    public void getDrawingRect(Rect outRect) {
8852        outRect.left = mScrollX;
8853        outRect.top = mScrollY;
8854        outRect.right = mScrollX + (mRight - mLeft);
8855        outRect.bottom = mScrollY + (mBottom - mTop);
8856    }
8857
8858    /**
8859     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8860     * raw width component (that is the result is masked by
8861     * {@link #MEASURED_SIZE_MASK}).
8862     *
8863     * @return The raw measured width of this view.
8864     */
8865    public final int getMeasuredWidth() {
8866        return mMeasuredWidth & MEASURED_SIZE_MASK;
8867    }
8868
8869    /**
8870     * Return the full width measurement information for this view as computed
8871     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8872     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8873     * This should be used during measurement and layout calculations only. Use
8874     * {@link #getWidth()} to see how wide a view is after layout.
8875     *
8876     * @return The measured width of this view as a bit mask.
8877     */
8878    public final int getMeasuredWidthAndState() {
8879        return mMeasuredWidth;
8880    }
8881
8882    /**
8883     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8884     * raw width component (that is the result is masked by
8885     * {@link #MEASURED_SIZE_MASK}).
8886     *
8887     * @return The raw measured height of this view.
8888     */
8889    public final int getMeasuredHeight() {
8890        return mMeasuredHeight & MEASURED_SIZE_MASK;
8891    }
8892
8893    /**
8894     * Return the full height measurement information for this view as computed
8895     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8896     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8897     * This should be used during measurement and layout calculations only. Use
8898     * {@link #getHeight()} to see how wide a view is after layout.
8899     *
8900     * @return The measured width of this view as a bit mask.
8901     */
8902    public final int getMeasuredHeightAndState() {
8903        return mMeasuredHeight;
8904    }
8905
8906    /**
8907     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8908     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8909     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8910     * and the height component is at the shifted bits
8911     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8912     */
8913    public final int getMeasuredState() {
8914        return (mMeasuredWidth&MEASURED_STATE_MASK)
8915                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8916                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8917    }
8918
8919    /**
8920     * The transform matrix of this view, which is calculated based on the current
8921     * roation, scale, and pivot properties.
8922     *
8923     * @see #getRotation()
8924     * @see #getScaleX()
8925     * @see #getScaleY()
8926     * @see #getPivotX()
8927     * @see #getPivotY()
8928     * @return The current transform matrix for the view
8929     */
8930    public Matrix getMatrix() {
8931        if (mTransformationInfo != null) {
8932            updateMatrix();
8933            return mTransformationInfo.mMatrix;
8934        }
8935        return Matrix.IDENTITY_MATRIX;
8936    }
8937
8938    /**
8939     * Utility function to determine if the value is far enough away from zero to be
8940     * considered non-zero.
8941     * @param value A floating point value to check for zero-ness
8942     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8943     */
8944    private static boolean nonzero(float value) {
8945        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8946    }
8947
8948    /**
8949     * Returns true if the transform matrix is the identity matrix.
8950     * Recomputes the matrix if necessary.
8951     *
8952     * @return True if the transform matrix is the identity matrix, false otherwise.
8953     */
8954    final boolean hasIdentityMatrix() {
8955        if (mTransformationInfo != null) {
8956            updateMatrix();
8957            return mTransformationInfo.mMatrixIsIdentity;
8958        }
8959        return true;
8960    }
8961
8962    void ensureTransformationInfo() {
8963        if (mTransformationInfo == null) {
8964            mTransformationInfo = new TransformationInfo();
8965        }
8966    }
8967
8968    /**
8969     * Recomputes the transform matrix if necessary.
8970     */
8971    private void updateMatrix() {
8972        final TransformationInfo info = mTransformationInfo;
8973        if (info == null) {
8974            return;
8975        }
8976        if (info.mMatrixDirty) {
8977            // transform-related properties have changed since the last time someone
8978            // asked for the matrix; recalculate it with the current values
8979
8980            // Figure out if we need to update the pivot point
8981            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8982                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8983                    info.mPrevWidth = mRight - mLeft;
8984                    info.mPrevHeight = mBottom - mTop;
8985                    info.mPivotX = info.mPrevWidth / 2f;
8986                    info.mPivotY = info.mPrevHeight / 2f;
8987                }
8988            }
8989            info.mMatrix.reset();
8990            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8991                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8992                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8993                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8994            } else {
8995                if (info.mCamera == null) {
8996                    info.mCamera = new Camera();
8997                    info.matrix3D = new Matrix();
8998                }
8999                info.mCamera.save();
9000                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
9001                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
9002                info.mCamera.getMatrix(info.matrix3D);
9003                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
9004                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
9005                        info.mPivotY + info.mTranslationY);
9006                info.mMatrix.postConcat(info.matrix3D);
9007                info.mCamera.restore();
9008            }
9009            info.mMatrixDirty = false;
9010            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9011            info.mInverseMatrixDirty = true;
9012        }
9013    }
9014
9015   /**
9016     * Utility method to retrieve the inverse of the current mMatrix property.
9017     * We cache the matrix to avoid recalculating it when transform properties
9018     * have not changed.
9019     *
9020     * @return The inverse of the current matrix of this view.
9021     */
9022    final Matrix getInverseMatrix() {
9023        final TransformationInfo info = mTransformationInfo;
9024        if (info != null) {
9025            updateMatrix();
9026            if (info.mInverseMatrixDirty) {
9027                if (info.mInverseMatrix == null) {
9028                    info.mInverseMatrix = new Matrix();
9029                }
9030                info.mMatrix.invert(info.mInverseMatrix);
9031                info.mInverseMatrixDirty = false;
9032            }
9033            return info.mInverseMatrix;
9034        }
9035        return Matrix.IDENTITY_MATRIX;
9036    }
9037
9038    /**
9039     * Gets the distance along the Z axis from the camera to this view.
9040     *
9041     * @see #setCameraDistance(float)
9042     *
9043     * @return The distance along the Z axis.
9044     */
9045    public float getCameraDistance() {
9046        ensureTransformationInfo();
9047        final float dpi = mResources.getDisplayMetrics().densityDpi;
9048        final TransformationInfo info = mTransformationInfo;
9049        if (info.mCamera == null) {
9050            info.mCamera = new Camera();
9051            info.matrix3D = new Matrix();
9052        }
9053        return -(info.mCamera.getLocationZ() * dpi);
9054    }
9055
9056    /**
9057     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9058     * views are drawn) from the camera to this view. The camera's distance
9059     * affects 3D transformations, for instance rotations around the X and Y
9060     * axis. If the rotationX or rotationY properties are changed and this view is
9061     * large (more than half the size of the screen), it is recommended to always
9062     * use a camera distance that's greater than the height (X axis rotation) or
9063     * the width (Y axis rotation) of this view.</p>
9064     *
9065     * <p>The distance of the camera from the view plane can have an affect on the
9066     * perspective distortion of the view when it is rotated around the x or y axis.
9067     * For example, a large distance will result in a large viewing angle, and there
9068     * will not be much perspective distortion of the view as it rotates. A short
9069     * distance may cause much more perspective distortion upon rotation, and can
9070     * also result in some drawing artifacts if the rotated view ends up partially
9071     * behind the camera (which is why the recommendation is to use a distance at
9072     * least as far as the size of the view, if the view is to be rotated.)</p>
9073     *
9074     * <p>The distance is expressed in "depth pixels." The default distance depends
9075     * on the screen density. For instance, on a medium density display, the
9076     * default distance is 1280. On a high density display, the default distance
9077     * is 1920.</p>
9078     *
9079     * <p>If you want to specify a distance that leads to visually consistent
9080     * results across various densities, use the following formula:</p>
9081     * <pre>
9082     * float scale = context.getResources().getDisplayMetrics().density;
9083     * view.setCameraDistance(distance * scale);
9084     * </pre>
9085     *
9086     * <p>The density scale factor of a high density display is 1.5,
9087     * and 1920 = 1280 * 1.5.</p>
9088     *
9089     * @param distance The distance in "depth pixels", if negative the opposite
9090     *        value is used
9091     *
9092     * @see #setRotationX(float)
9093     * @see #setRotationY(float)
9094     */
9095    public void setCameraDistance(float distance) {
9096        invalidateViewProperty(true, false);
9097
9098        ensureTransformationInfo();
9099        final float dpi = mResources.getDisplayMetrics().densityDpi;
9100        final TransformationInfo info = mTransformationInfo;
9101        if (info.mCamera == null) {
9102            info.mCamera = new Camera();
9103            info.matrix3D = new Matrix();
9104        }
9105
9106        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9107        info.mMatrixDirty = true;
9108
9109        invalidateViewProperty(false, false);
9110        if (mDisplayList != null) {
9111            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9112        }
9113        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9114            // View was rejected last time it was drawn by its parent; this may have changed
9115            invalidateParentIfNeeded();
9116        }
9117    }
9118
9119    /**
9120     * The degrees that the view is rotated around the pivot point.
9121     *
9122     * @see #setRotation(float)
9123     * @see #getPivotX()
9124     * @see #getPivotY()
9125     *
9126     * @return The degrees of rotation.
9127     */
9128    @ViewDebug.ExportedProperty(category = "drawing")
9129    public float getRotation() {
9130        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9131    }
9132
9133    /**
9134     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9135     * result in clockwise rotation.
9136     *
9137     * @param rotation The degrees of rotation.
9138     *
9139     * @see #getRotation()
9140     * @see #getPivotX()
9141     * @see #getPivotY()
9142     * @see #setRotationX(float)
9143     * @see #setRotationY(float)
9144     *
9145     * @attr ref android.R.styleable#View_rotation
9146     */
9147    public void setRotation(float rotation) {
9148        ensureTransformationInfo();
9149        final TransformationInfo info = mTransformationInfo;
9150        if (info.mRotation != rotation) {
9151            // Double-invalidation is necessary to capture view's old and new areas
9152            invalidateViewProperty(true, false);
9153            info.mRotation = rotation;
9154            info.mMatrixDirty = true;
9155            invalidateViewProperty(false, true);
9156            if (mDisplayList != null) {
9157                mDisplayList.setRotation(rotation);
9158            }
9159            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9160                // View was rejected last time it was drawn by its parent; this may have changed
9161                invalidateParentIfNeeded();
9162            }
9163        }
9164    }
9165
9166    /**
9167     * The degrees that the view is rotated around the vertical axis through the pivot point.
9168     *
9169     * @see #getPivotX()
9170     * @see #getPivotY()
9171     * @see #setRotationY(float)
9172     *
9173     * @return The degrees of Y rotation.
9174     */
9175    @ViewDebug.ExportedProperty(category = "drawing")
9176    public float getRotationY() {
9177        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9178    }
9179
9180    /**
9181     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9182     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9183     * down the y axis.
9184     *
9185     * When rotating large views, it is recommended to adjust the camera distance
9186     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9187     *
9188     * @param rotationY The degrees of Y rotation.
9189     *
9190     * @see #getRotationY()
9191     * @see #getPivotX()
9192     * @see #getPivotY()
9193     * @see #setRotation(float)
9194     * @see #setRotationX(float)
9195     * @see #setCameraDistance(float)
9196     *
9197     * @attr ref android.R.styleable#View_rotationY
9198     */
9199    public void setRotationY(float rotationY) {
9200        ensureTransformationInfo();
9201        final TransformationInfo info = mTransformationInfo;
9202        if (info.mRotationY != rotationY) {
9203            invalidateViewProperty(true, false);
9204            info.mRotationY = rotationY;
9205            info.mMatrixDirty = true;
9206            invalidateViewProperty(false, true);
9207            if (mDisplayList != null) {
9208                mDisplayList.setRotationY(rotationY);
9209            }
9210            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9211                // View was rejected last time it was drawn by its parent; this may have changed
9212                invalidateParentIfNeeded();
9213            }
9214        }
9215    }
9216
9217    /**
9218     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9219     *
9220     * @see #getPivotX()
9221     * @see #getPivotY()
9222     * @see #setRotationX(float)
9223     *
9224     * @return The degrees of X rotation.
9225     */
9226    @ViewDebug.ExportedProperty(category = "drawing")
9227    public float getRotationX() {
9228        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9229    }
9230
9231    /**
9232     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9233     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9234     * x axis.
9235     *
9236     * When rotating large views, it is recommended to adjust the camera distance
9237     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9238     *
9239     * @param rotationX The degrees of X rotation.
9240     *
9241     * @see #getRotationX()
9242     * @see #getPivotX()
9243     * @see #getPivotY()
9244     * @see #setRotation(float)
9245     * @see #setRotationY(float)
9246     * @see #setCameraDistance(float)
9247     *
9248     * @attr ref android.R.styleable#View_rotationX
9249     */
9250    public void setRotationX(float rotationX) {
9251        ensureTransformationInfo();
9252        final TransformationInfo info = mTransformationInfo;
9253        if (info.mRotationX != rotationX) {
9254            invalidateViewProperty(true, false);
9255            info.mRotationX = rotationX;
9256            info.mMatrixDirty = true;
9257            invalidateViewProperty(false, true);
9258            if (mDisplayList != null) {
9259                mDisplayList.setRotationX(rotationX);
9260            }
9261            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9262                // View was rejected last time it was drawn by its parent; this may have changed
9263                invalidateParentIfNeeded();
9264            }
9265        }
9266    }
9267
9268    /**
9269     * The amount that the view is scaled in x around the pivot point, as a proportion of
9270     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9271     *
9272     * <p>By default, this is 1.0f.
9273     *
9274     * @see #getPivotX()
9275     * @see #getPivotY()
9276     * @return The scaling factor.
9277     */
9278    @ViewDebug.ExportedProperty(category = "drawing")
9279    public float getScaleX() {
9280        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9281    }
9282
9283    /**
9284     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9285     * the view's unscaled width. A value of 1 means that no scaling is applied.
9286     *
9287     * @param scaleX The scaling factor.
9288     * @see #getPivotX()
9289     * @see #getPivotY()
9290     *
9291     * @attr ref android.R.styleable#View_scaleX
9292     */
9293    public void setScaleX(float scaleX) {
9294        ensureTransformationInfo();
9295        final TransformationInfo info = mTransformationInfo;
9296        if (info.mScaleX != scaleX) {
9297            invalidateViewProperty(true, false);
9298            info.mScaleX = scaleX;
9299            info.mMatrixDirty = true;
9300            invalidateViewProperty(false, true);
9301            if (mDisplayList != null) {
9302                mDisplayList.setScaleX(scaleX);
9303            }
9304            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9305                // View was rejected last time it was drawn by its parent; this may have changed
9306                invalidateParentIfNeeded();
9307            }
9308        }
9309    }
9310
9311    /**
9312     * The amount that the view is scaled in y around the pivot point, as a proportion of
9313     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9314     *
9315     * <p>By default, this is 1.0f.
9316     *
9317     * @see #getPivotX()
9318     * @see #getPivotY()
9319     * @return The scaling factor.
9320     */
9321    @ViewDebug.ExportedProperty(category = "drawing")
9322    public float getScaleY() {
9323        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9324    }
9325
9326    /**
9327     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9328     * the view's unscaled width. A value of 1 means that no scaling is applied.
9329     *
9330     * @param scaleY The scaling factor.
9331     * @see #getPivotX()
9332     * @see #getPivotY()
9333     *
9334     * @attr ref android.R.styleable#View_scaleY
9335     */
9336    public void setScaleY(float scaleY) {
9337        ensureTransformationInfo();
9338        final TransformationInfo info = mTransformationInfo;
9339        if (info.mScaleY != scaleY) {
9340            invalidateViewProperty(true, false);
9341            info.mScaleY = scaleY;
9342            info.mMatrixDirty = true;
9343            invalidateViewProperty(false, true);
9344            if (mDisplayList != null) {
9345                mDisplayList.setScaleY(scaleY);
9346            }
9347            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9348                // View was rejected last time it was drawn by its parent; this may have changed
9349                invalidateParentIfNeeded();
9350            }
9351        }
9352    }
9353
9354    /**
9355     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9356     * and {@link #setScaleX(float) scaled}.
9357     *
9358     * @see #getRotation()
9359     * @see #getScaleX()
9360     * @see #getScaleY()
9361     * @see #getPivotY()
9362     * @return The x location of the pivot point.
9363     *
9364     * @attr ref android.R.styleable#View_transformPivotX
9365     */
9366    @ViewDebug.ExportedProperty(category = "drawing")
9367    public float getPivotX() {
9368        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9369    }
9370
9371    /**
9372     * Sets the x location of the point around which the view is
9373     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9374     * By default, the pivot point is centered on the object.
9375     * Setting this property disables this behavior and causes the view to use only the
9376     * explicitly set pivotX and pivotY values.
9377     *
9378     * @param pivotX The x location of the pivot point.
9379     * @see #getRotation()
9380     * @see #getScaleX()
9381     * @see #getScaleY()
9382     * @see #getPivotY()
9383     *
9384     * @attr ref android.R.styleable#View_transformPivotX
9385     */
9386    public void setPivotX(float pivotX) {
9387        ensureTransformationInfo();
9388        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9389        final TransformationInfo info = mTransformationInfo;
9390        if (info.mPivotX != pivotX) {
9391            invalidateViewProperty(true, false);
9392            info.mPivotX = pivotX;
9393            info.mMatrixDirty = true;
9394            invalidateViewProperty(false, true);
9395            if (mDisplayList != null) {
9396                mDisplayList.setPivotX(pivotX);
9397            }
9398            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9399                // View was rejected last time it was drawn by its parent; this may have changed
9400                invalidateParentIfNeeded();
9401            }
9402        }
9403    }
9404
9405    /**
9406     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9407     * and {@link #setScaleY(float) scaled}.
9408     *
9409     * @see #getRotation()
9410     * @see #getScaleX()
9411     * @see #getScaleY()
9412     * @see #getPivotY()
9413     * @return The y location of the pivot point.
9414     *
9415     * @attr ref android.R.styleable#View_transformPivotY
9416     */
9417    @ViewDebug.ExportedProperty(category = "drawing")
9418    public float getPivotY() {
9419        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9420    }
9421
9422    /**
9423     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9424     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9425     * Setting this property disables this behavior and causes the view to use only the
9426     * explicitly set pivotX and pivotY values.
9427     *
9428     * @param pivotY The y location of the pivot point.
9429     * @see #getRotation()
9430     * @see #getScaleX()
9431     * @see #getScaleY()
9432     * @see #getPivotY()
9433     *
9434     * @attr ref android.R.styleable#View_transformPivotY
9435     */
9436    public void setPivotY(float pivotY) {
9437        ensureTransformationInfo();
9438        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9439        final TransformationInfo info = mTransformationInfo;
9440        if (info.mPivotY != pivotY) {
9441            invalidateViewProperty(true, false);
9442            info.mPivotY = pivotY;
9443            info.mMatrixDirty = true;
9444            invalidateViewProperty(false, true);
9445            if (mDisplayList != null) {
9446                mDisplayList.setPivotY(pivotY);
9447            }
9448            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9449                // View was rejected last time it was drawn by its parent; this may have changed
9450                invalidateParentIfNeeded();
9451            }
9452        }
9453    }
9454
9455    /**
9456     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9457     * completely transparent and 1 means the view is completely opaque.
9458     *
9459     * <p>By default this is 1.0f.
9460     * @return The opacity of the view.
9461     */
9462    @ViewDebug.ExportedProperty(category = "drawing")
9463    public float getAlpha() {
9464        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9465    }
9466
9467    /**
9468     * Returns whether this View has content which overlaps. This function, intended to be
9469     * overridden by specific View types, is an optimization when alpha is set on a view. If
9470     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9471     * and then composited it into place, which can be expensive. If the view has no overlapping
9472     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9473     * An example of overlapping rendering is a TextView with a background image, such as a
9474     * Button. An example of non-overlapping rendering is a TextView with no background, or
9475     * an ImageView with only the foreground image. The default implementation returns true;
9476     * subclasses should override if they have cases which can be optimized.
9477     *
9478     * @return true if the content in this view might overlap, false otherwise.
9479     */
9480    public boolean hasOverlappingRendering() {
9481        return true;
9482    }
9483
9484    /**
9485     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9486     * completely transparent and 1 means the view is completely opaque.</p>
9487     *
9488     * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant
9489     * performance implications, especially for large views. It is best to use the alpha property
9490     * sparingly and transiently, as in the case of fading animations.</p>
9491     *
9492     * <p>For a view with a frequently changing alpha, such as during a fading animation, it is
9493     * strongly recommended for performance reasons to either override
9494     * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a
9495     * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p>
9496     *
9497     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9498     * responsible for applying the opacity itself.</p>
9499     *
9500     * <p>Note that if the view is backed by a
9501     * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a
9502     * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than
9503     * 1.0 will supercede the alpha of the layer paint.</p>
9504     *
9505     * @param alpha The opacity of the view.
9506     *
9507     * @see #hasOverlappingRendering()
9508     * @see #setLayerType(int, android.graphics.Paint)
9509     *
9510     * @attr ref android.R.styleable#View_alpha
9511     */
9512    public void setAlpha(float alpha) {
9513        ensureTransformationInfo();
9514        if (mTransformationInfo.mAlpha != alpha) {
9515            mTransformationInfo.mAlpha = alpha;
9516            if (onSetAlpha((int) (alpha * 255))) {
9517                mPrivateFlags |= PFLAG_ALPHA_SET;
9518                // subclass is handling alpha - don't optimize rendering cache invalidation
9519                invalidateParentCaches();
9520                invalidate(true);
9521            } else {
9522                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9523                invalidateViewProperty(true, false);
9524                if (mDisplayList != null) {
9525                    mDisplayList.setAlpha(alpha);
9526                }
9527            }
9528        }
9529    }
9530
9531    /**
9532     * Faster version of setAlpha() which performs the same steps except there are
9533     * no calls to invalidate(). The caller of this function should perform proper invalidation
9534     * on the parent and this object. The return value indicates whether the subclass handles
9535     * alpha (the return value for onSetAlpha()).
9536     *
9537     * @param alpha The new value for the alpha property
9538     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9539     *         the new value for the alpha property is different from the old value
9540     */
9541    boolean setAlphaNoInvalidation(float alpha) {
9542        ensureTransformationInfo();
9543        if (mTransformationInfo.mAlpha != alpha) {
9544            mTransformationInfo.mAlpha = alpha;
9545            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9546            if (subclassHandlesAlpha) {
9547                mPrivateFlags |= PFLAG_ALPHA_SET;
9548                return true;
9549            } else {
9550                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9551                if (mDisplayList != null) {
9552                    mDisplayList.setAlpha(alpha);
9553                }
9554            }
9555        }
9556        return false;
9557    }
9558
9559    /**
9560     * Top position of this view relative to its parent.
9561     *
9562     * @return The top of this view, in pixels.
9563     */
9564    @ViewDebug.CapturedViewProperty
9565    public final int getTop() {
9566        return mTop;
9567    }
9568
9569    /**
9570     * Sets the top position of this view relative to its parent. This method is meant to be called
9571     * by the layout system and should not generally be called otherwise, because the property
9572     * may be changed at any time by the layout.
9573     *
9574     * @param top The top of this view, in pixels.
9575     */
9576    public final void setTop(int top) {
9577        if (top != mTop) {
9578            updateMatrix();
9579            final boolean matrixIsIdentity = mTransformationInfo == null
9580                    || mTransformationInfo.mMatrixIsIdentity;
9581            if (matrixIsIdentity) {
9582                if (mAttachInfo != null) {
9583                    int minTop;
9584                    int yLoc;
9585                    if (top < mTop) {
9586                        minTop = top;
9587                        yLoc = top - mTop;
9588                    } else {
9589                        minTop = mTop;
9590                        yLoc = 0;
9591                    }
9592                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9593                }
9594            } else {
9595                // Double-invalidation is necessary to capture view's old and new areas
9596                invalidate(true);
9597            }
9598
9599            int width = mRight - mLeft;
9600            int oldHeight = mBottom - mTop;
9601
9602            mTop = top;
9603            if (mDisplayList != null) {
9604                mDisplayList.setTop(mTop);
9605            }
9606
9607            sizeChange(width, mBottom - mTop, width, oldHeight);
9608
9609            if (!matrixIsIdentity) {
9610                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9611                    // A change in dimension means an auto-centered pivot point changes, too
9612                    mTransformationInfo.mMatrixDirty = true;
9613                }
9614                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9615                invalidate(true);
9616            }
9617            mBackgroundSizeChanged = true;
9618            invalidateParentIfNeeded();
9619            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9620                // View was rejected last time it was drawn by its parent; this may have changed
9621                invalidateParentIfNeeded();
9622            }
9623        }
9624    }
9625
9626    /**
9627     * Bottom position of this view relative to its parent.
9628     *
9629     * @return The bottom of this view, in pixels.
9630     */
9631    @ViewDebug.CapturedViewProperty
9632    public final int getBottom() {
9633        return mBottom;
9634    }
9635
9636    /**
9637     * True if this view has changed since the last time being drawn.
9638     *
9639     * @return The dirty state of this view.
9640     */
9641    public boolean isDirty() {
9642        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9643    }
9644
9645    /**
9646     * Sets the bottom position of this view relative to its parent. This method is meant to be
9647     * called by the layout system and should not generally be called otherwise, because the
9648     * property may be changed at any time by the layout.
9649     *
9650     * @param bottom The bottom of this view, in pixels.
9651     */
9652    public final void setBottom(int bottom) {
9653        if (bottom != mBottom) {
9654            updateMatrix();
9655            final boolean matrixIsIdentity = mTransformationInfo == null
9656                    || mTransformationInfo.mMatrixIsIdentity;
9657            if (matrixIsIdentity) {
9658                if (mAttachInfo != null) {
9659                    int maxBottom;
9660                    if (bottom < mBottom) {
9661                        maxBottom = mBottom;
9662                    } else {
9663                        maxBottom = bottom;
9664                    }
9665                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9666                }
9667            } else {
9668                // Double-invalidation is necessary to capture view's old and new areas
9669                invalidate(true);
9670            }
9671
9672            int width = mRight - mLeft;
9673            int oldHeight = mBottom - mTop;
9674
9675            mBottom = bottom;
9676            if (mDisplayList != null) {
9677                mDisplayList.setBottom(mBottom);
9678            }
9679
9680            sizeChange(width, mBottom - mTop, width, oldHeight);
9681
9682            if (!matrixIsIdentity) {
9683                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9684                    // A change in dimension means an auto-centered pivot point changes, too
9685                    mTransformationInfo.mMatrixDirty = true;
9686                }
9687                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9688                invalidate(true);
9689            }
9690            mBackgroundSizeChanged = true;
9691            invalidateParentIfNeeded();
9692            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9693                // View was rejected last time it was drawn by its parent; this may have changed
9694                invalidateParentIfNeeded();
9695            }
9696        }
9697    }
9698
9699    /**
9700     * Left position of this view relative to its parent.
9701     *
9702     * @return The left edge of this view, in pixels.
9703     */
9704    @ViewDebug.CapturedViewProperty
9705    public final int getLeft() {
9706        return mLeft;
9707    }
9708
9709    /**
9710     * Sets the left position of this view relative to its parent. This method is meant to be called
9711     * by the layout system and should not generally be called otherwise, because the property
9712     * may be changed at any time by the layout.
9713     *
9714     * @param left The bottom of this view, in pixels.
9715     */
9716    public final void setLeft(int left) {
9717        if (left != mLeft) {
9718            updateMatrix();
9719            final boolean matrixIsIdentity = mTransformationInfo == null
9720                    || mTransformationInfo.mMatrixIsIdentity;
9721            if (matrixIsIdentity) {
9722                if (mAttachInfo != null) {
9723                    int minLeft;
9724                    int xLoc;
9725                    if (left < mLeft) {
9726                        minLeft = left;
9727                        xLoc = left - mLeft;
9728                    } else {
9729                        minLeft = mLeft;
9730                        xLoc = 0;
9731                    }
9732                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9733                }
9734            } else {
9735                // Double-invalidation is necessary to capture view's old and new areas
9736                invalidate(true);
9737            }
9738
9739            int oldWidth = mRight - mLeft;
9740            int height = mBottom - mTop;
9741
9742            mLeft = left;
9743            if (mDisplayList != null) {
9744                mDisplayList.setLeft(left);
9745            }
9746
9747            sizeChange(mRight - mLeft, height, oldWidth, height);
9748
9749            if (!matrixIsIdentity) {
9750                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9751                    // A change in dimension means an auto-centered pivot point changes, too
9752                    mTransformationInfo.mMatrixDirty = true;
9753                }
9754                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9755                invalidate(true);
9756            }
9757            mBackgroundSizeChanged = true;
9758            invalidateParentIfNeeded();
9759            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9760                // View was rejected last time it was drawn by its parent; this may have changed
9761                invalidateParentIfNeeded();
9762            }
9763        }
9764    }
9765
9766    /**
9767     * Right position of this view relative to its parent.
9768     *
9769     * @return The right edge of this view, in pixels.
9770     */
9771    @ViewDebug.CapturedViewProperty
9772    public final int getRight() {
9773        return mRight;
9774    }
9775
9776    /**
9777     * Sets the right position of this view relative to its parent. This method is meant to be called
9778     * by the layout system and should not generally be called otherwise, because the property
9779     * may be changed at any time by the layout.
9780     *
9781     * @param right The bottom of this view, in pixels.
9782     */
9783    public final void setRight(int right) {
9784        if (right != mRight) {
9785            updateMatrix();
9786            final boolean matrixIsIdentity = mTransformationInfo == null
9787                    || mTransformationInfo.mMatrixIsIdentity;
9788            if (matrixIsIdentity) {
9789                if (mAttachInfo != null) {
9790                    int maxRight;
9791                    if (right < mRight) {
9792                        maxRight = mRight;
9793                    } else {
9794                        maxRight = right;
9795                    }
9796                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9797                }
9798            } else {
9799                // Double-invalidation is necessary to capture view's old and new areas
9800                invalidate(true);
9801            }
9802
9803            int oldWidth = mRight - mLeft;
9804            int height = mBottom - mTop;
9805
9806            mRight = right;
9807            if (mDisplayList != null) {
9808                mDisplayList.setRight(mRight);
9809            }
9810
9811            sizeChange(mRight - mLeft, height, oldWidth, height);
9812
9813            if (!matrixIsIdentity) {
9814                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9815                    // A change in dimension means an auto-centered pivot point changes, too
9816                    mTransformationInfo.mMatrixDirty = true;
9817                }
9818                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9819                invalidate(true);
9820            }
9821            mBackgroundSizeChanged = true;
9822            invalidateParentIfNeeded();
9823            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9824                // View was rejected last time it was drawn by its parent; this may have changed
9825                invalidateParentIfNeeded();
9826            }
9827        }
9828    }
9829
9830    /**
9831     * The visual x position of this view, in pixels. This is equivalent to the
9832     * {@link #setTranslationX(float) translationX} property plus the current
9833     * {@link #getLeft() left} property.
9834     *
9835     * @return The visual x position of this view, in pixels.
9836     */
9837    @ViewDebug.ExportedProperty(category = "drawing")
9838    public float getX() {
9839        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9840    }
9841
9842    /**
9843     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9844     * {@link #setTranslationX(float) translationX} property to be the difference between
9845     * the x value passed in and the current {@link #getLeft() left} property.
9846     *
9847     * @param x The visual x position of this view, in pixels.
9848     */
9849    public void setX(float x) {
9850        setTranslationX(x - mLeft);
9851    }
9852
9853    /**
9854     * The visual y position of this view, in pixels. This is equivalent to the
9855     * {@link #setTranslationY(float) translationY} property plus the current
9856     * {@link #getTop() top} property.
9857     *
9858     * @return The visual y position of this view, in pixels.
9859     */
9860    @ViewDebug.ExportedProperty(category = "drawing")
9861    public float getY() {
9862        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9863    }
9864
9865    /**
9866     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9867     * {@link #setTranslationY(float) translationY} property to be the difference between
9868     * the y value passed in and the current {@link #getTop() top} property.
9869     *
9870     * @param y The visual y position of this view, in pixels.
9871     */
9872    public void setY(float y) {
9873        setTranslationY(y - mTop);
9874    }
9875
9876
9877    /**
9878     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9879     * This position is post-layout, in addition to wherever the object's
9880     * layout placed it.
9881     *
9882     * @return The horizontal position of this view relative to its left position, in pixels.
9883     */
9884    @ViewDebug.ExportedProperty(category = "drawing")
9885    public float getTranslationX() {
9886        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9887    }
9888
9889    /**
9890     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9891     * This effectively positions the object post-layout, in addition to wherever the object's
9892     * layout placed it.
9893     *
9894     * @param translationX The horizontal position of this view relative to its left position,
9895     * in pixels.
9896     *
9897     * @attr ref android.R.styleable#View_translationX
9898     */
9899    public void setTranslationX(float translationX) {
9900        ensureTransformationInfo();
9901        final TransformationInfo info = mTransformationInfo;
9902        if (info.mTranslationX != translationX) {
9903            // Double-invalidation is necessary to capture view's old and new areas
9904            invalidateViewProperty(true, false);
9905            info.mTranslationX = translationX;
9906            info.mMatrixDirty = true;
9907            invalidateViewProperty(false, true);
9908            if (mDisplayList != null) {
9909                mDisplayList.setTranslationX(translationX);
9910            }
9911            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9912                // View was rejected last time it was drawn by its parent; this may have changed
9913                invalidateParentIfNeeded();
9914            }
9915        }
9916    }
9917
9918    /**
9919     * The horizontal location of this view relative to its {@link #getTop() top} position.
9920     * This position is post-layout, in addition to wherever the object's
9921     * layout placed it.
9922     *
9923     * @return The vertical position of this view relative to its top position,
9924     * in pixels.
9925     */
9926    @ViewDebug.ExportedProperty(category = "drawing")
9927    public float getTranslationY() {
9928        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9929    }
9930
9931    /**
9932     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9933     * This effectively positions the object post-layout, in addition to wherever the object's
9934     * layout placed it.
9935     *
9936     * @param translationY The vertical position of this view relative to its top position,
9937     * in pixels.
9938     *
9939     * @attr ref android.R.styleable#View_translationY
9940     */
9941    public void setTranslationY(float translationY) {
9942        ensureTransformationInfo();
9943        final TransformationInfo info = mTransformationInfo;
9944        if (info.mTranslationY != translationY) {
9945            invalidateViewProperty(true, false);
9946            info.mTranslationY = translationY;
9947            info.mMatrixDirty = true;
9948            invalidateViewProperty(false, true);
9949            if (mDisplayList != null) {
9950                mDisplayList.setTranslationY(translationY);
9951            }
9952            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9953                // View was rejected last time it was drawn by its parent; this may have changed
9954                invalidateParentIfNeeded();
9955            }
9956        }
9957    }
9958
9959    /**
9960     * Hit rectangle in parent's coordinates
9961     *
9962     * @param outRect The hit rectangle of the view.
9963     */
9964    public void getHitRect(Rect outRect) {
9965        updateMatrix();
9966        final TransformationInfo info = mTransformationInfo;
9967        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9968            outRect.set(mLeft, mTop, mRight, mBottom);
9969        } else {
9970            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9971            tmpRect.set(0, 0, getWidth(), getHeight());
9972            info.mMatrix.mapRect(tmpRect);
9973            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9974                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9975        }
9976    }
9977
9978    /**
9979     * Determines whether the given point, in local coordinates is inside the view.
9980     */
9981    /*package*/ final boolean pointInView(float localX, float localY) {
9982        return localX >= 0 && localX < (mRight - mLeft)
9983                && localY >= 0 && localY < (mBottom - mTop);
9984    }
9985
9986    /**
9987     * Utility method to determine whether the given point, in local coordinates,
9988     * is inside the view, where the area of the view is expanded by the slop factor.
9989     * This method is called while processing touch-move events to determine if the event
9990     * is still within the view.
9991     */
9992    private boolean pointInView(float localX, float localY, float slop) {
9993        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9994                localY < ((mBottom - mTop) + slop);
9995    }
9996
9997    /**
9998     * When a view has focus and the user navigates away from it, the next view is searched for
9999     * starting from the rectangle filled in by this method.
10000     *
10001     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
10002     * of the view.  However, if your view maintains some idea of internal selection,
10003     * such as a cursor, or a selected row or column, you should override this method and
10004     * fill in a more specific rectangle.
10005     *
10006     * @param r The rectangle to fill in, in this view's coordinates.
10007     */
10008    public void getFocusedRect(Rect r) {
10009        getDrawingRect(r);
10010    }
10011
10012    /**
10013     * If some part of this view is not clipped by any of its parents, then
10014     * return that area in r in global (root) coordinates. To convert r to local
10015     * coordinates (without taking possible View rotations into account), offset
10016     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10017     * If the view is completely clipped or translated out, return false.
10018     *
10019     * @param r If true is returned, r holds the global coordinates of the
10020     *        visible portion of this view.
10021     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10022     *        between this view and its root. globalOffet may be null.
10023     * @return true if r is non-empty (i.e. part of the view is visible at the
10024     *         root level.
10025     */
10026    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10027        int width = mRight - mLeft;
10028        int height = mBottom - mTop;
10029        if (width > 0 && height > 0) {
10030            r.set(0, 0, width, height);
10031            if (globalOffset != null) {
10032                globalOffset.set(-mScrollX, -mScrollY);
10033            }
10034            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10035        }
10036        return false;
10037    }
10038
10039    public final boolean getGlobalVisibleRect(Rect r) {
10040        return getGlobalVisibleRect(r, null);
10041    }
10042
10043    public final boolean getLocalVisibleRect(Rect r) {
10044        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10045        if (getGlobalVisibleRect(r, offset)) {
10046            r.offset(-offset.x, -offset.y); // make r local
10047            return true;
10048        }
10049        return false;
10050    }
10051
10052    /**
10053     * Offset this view's vertical location by the specified number of pixels.
10054     *
10055     * @param offset the number of pixels to offset the view by
10056     */
10057    public void offsetTopAndBottom(int offset) {
10058        if (offset != 0) {
10059            updateMatrix();
10060            final boolean matrixIsIdentity = mTransformationInfo == null
10061                    || mTransformationInfo.mMatrixIsIdentity;
10062            if (matrixIsIdentity) {
10063                if (mDisplayList != null) {
10064                    invalidateViewProperty(false, false);
10065                } else {
10066                    final ViewParent p = mParent;
10067                    if (p != null && mAttachInfo != null) {
10068                        final Rect r = mAttachInfo.mTmpInvalRect;
10069                        int minTop;
10070                        int maxBottom;
10071                        int yLoc;
10072                        if (offset < 0) {
10073                            minTop = mTop + offset;
10074                            maxBottom = mBottom;
10075                            yLoc = offset;
10076                        } else {
10077                            minTop = mTop;
10078                            maxBottom = mBottom + offset;
10079                            yLoc = 0;
10080                        }
10081                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10082                        p.invalidateChild(this, r);
10083                    }
10084                }
10085            } else {
10086                invalidateViewProperty(false, false);
10087            }
10088
10089            mTop += offset;
10090            mBottom += offset;
10091            if (mDisplayList != null) {
10092                mDisplayList.offsetTopAndBottom(offset);
10093                invalidateViewProperty(false, false);
10094            } else {
10095                if (!matrixIsIdentity) {
10096                    invalidateViewProperty(false, true);
10097                }
10098                invalidateParentIfNeeded();
10099            }
10100        }
10101    }
10102
10103    /**
10104     * Offset this view's horizontal location by the specified amount of pixels.
10105     *
10106     * @param offset the numer of pixels to offset the view by
10107     */
10108    public void offsetLeftAndRight(int offset) {
10109        if (offset != 0) {
10110            updateMatrix();
10111            final boolean matrixIsIdentity = mTransformationInfo == null
10112                    || mTransformationInfo.mMatrixIsIdentity;
10113            if (matrixIsIdentity) {
10114                if (mDisplayList != null) {
10115                    invalidateViewProperty(false, false);
10116                } else {
10117                    final ViewParent p = mParent;
10118                    if (p != null && mAttachInfo != null) {
10119                        final Rect r = mAttachInfo.mTmpInvalRect;
10120                        int minLeft;
10121                        int maxRight;
10122                        if (offset < 0) {
10123                            minLeft = mLeft + offset;
10124                            maxRight = mRight;
10125                        } else {
10126                            minLeft = mLeft;
10127                            maxRight = mRight + offset;
10128                        }
10129                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10130                        p.invalidateChild(this, r);
10131                    }
10132                }
10133            } else {
10134                invalidateViewProperty(false, false);
10135            }
10136
10137            mLeft += offset;
10138            mRight += offset;
10139            if (mDisplayList != null) {
10140                mDisplayList.offsetLeftAndRight(offset);
10141                invalidateViewProperty(false, false);
10142            } else {
10143                if (!matrixIsIdentity) {
10144                    invalidateViewProperty(false, true);
10145                }
10146                invalidateParentIfNeeded();
10147            }
10148        }
10149    }
10150
10151    /**
10152     * Get the LayoutParams associated with this view. All views should have
10153     * layout parameters. These supply parameters to the <i>parent</i> of this
10154     * view specifying how it should be arranged. There are many subclasses of
10155     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10156     * of ViewGroup that are responsible for arranging their children.
10157     *
10158     * This method may return null if this View is not attached to a parent
10159     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10160     * was not invoked successfully. When a View is attached to a parent
10161     * ViewGroup, this method must not return null.
10162     *
10163     * @return The LayoutParams associated with this view, or null if no
10164     *         parameters have been set yet
10165     */
10166    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10167    public ViewGroup.LayoutParams getLayoutParams() {
10168        return mLayoutParams;
10169    }
10170
10171    /**
10172     * Set the layout parameters associated with this view. These supply
10173     * parameters to the <i>parent</i> of this view specifying how it should be
10174     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10175     * correspond to the different subclasses of ViewGroup that are responsible
10176     * for arranging their children.
10177     *
10178     * @param params The layout parameters for this view, cannot be null
10179     */
10180    public void setLayoutParams(ViewGroup.LayoutParams params) {
10181        if (params == null) {
10182            throw new NullPointerException("Layout parameters cannot be null");
10183        }
10184        mLayoutParams = params;
10185        resolveLayoutParams();
10186        if (mParent instanceof ViewGroup) {
10187            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10188        }
10189        requestLayout();
10190    }
10191
10192    /**
10193     * Resolve the layout parameters depending on the resolved layout direction
10194     *
10195     * @hide
10196     */
10197    public void resolveLayoutParams() {
10198        if (mLayoutParams != null) {
10199            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10200        }
10201    }
10202
10203    /**
10204     * Set the scrolled position of your view. This will cause a call to
10205     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10206     * invalidated.
10207     * @param x the x position to scroll to
10208     * @param y the y position to scroll to
10209     */
10210    public void scrollTo(int x, int y) {
10211        if (mScrollX != x || mScrollY != y) {
10212            int oldX = mScrollX;
10213            int oldY = mScrollY;
10214            mScrollX = x;
10215            mScrollY = y;
10216            invalidateParentCaches();
10217            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10218            if (!awakenScrollBars()) {
10219                postInvalidateOnAnimation();
10220            }
10221        }
10222    }
10223
10224    /**
10225     * Move the scrolled position of your view. This will cause a call to
10226     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10227     * invalidated.
10228     * @param x the amount of pixels to scroll by horizontally
10229     * @param y the amount of pixels to scroll by vertically
10230     */
10231    public void scrollBy(int x, int y) {
10232        scrollTo(mScrollX + x, mScrollY + y);
10233    }
10234
10235    /**
10236     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10237     * animation to fade the scrollbars out after a default delay. If a subclass
10238     * provides animated scrolling, the start delay should equal the duration
10239     * of the scrolling animation.</p>
10240     *
10241     * <p>The animation starts only if at least one of the scrollbars is
10242     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10243     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10244     * this method returns true, and false otherwise. If the animation is
10245     * started, this method calls {@link #invalidate()}; in that case the
10246     * caller should not call {@link #invalidate()}.</p>
10247     *
10248     * <p>This method should be invoked every time a subclass directly updates
10249     * the scroll parameters.</p>
10250     *
10251     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10252     * and {@link #scrollTo(int, int)}.</p>
10253     *
10254     * @return true if the animation is played, false otherwise
10255     *
10256     * @see #awakenScrollBars(int)
10257     * @see #scrollBy(int, int)
10258     * @see #scrollTo(int, int)
10259     * @see #isHorizontalScrollBarEnabled()
10260     * @see #isVerticalScrollBarEnabled()
10261     * @see #setHorizontalScrollBarEnabled(boolean)
10262     * @see #setVerticalScrollBarEnabled(boolean)
10263     */
10264    protected boolean awakenScrollBars() {
10265        return mScrollCache != null &&
10266                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10267    }
10268
10269    /**
10270     * Trigger the scrollbars to draw.
10271     * This method differs from awakenScrollBars() only in its default duration.
10272     * initialAwakenScrollBars() will show the scroll bars for longer than
10273     * usual to give the user more of a chance to notice them.
10274     *
10275     * @return true if the animation is played, false otherwise.
10276     */
10277    private boolean initialAwakenScrollBars() {
10278        return mScrollCache != null &&
10279                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10280    }
10281
10282    /**
10283     * <p>
10284     * Trigger the scrollbars to draw. When invoked this method starts an
10285     * animation to fade the scrollbars out after a fixed delay. If a subclass
10286     * provides animated scrolling, the start delay should equal the duration of
10287     * the scrolling animation.
10288     * </p>
10289     *
10290     * <p>
10291     * The animation starts only if at least one of the scrollbars is enabled,
10292     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10293     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10294     * this method returns true, and false otherwise. If the animation is
10295     * started, this method calls {@link #invalidate()}; in that case the caller
10296     * should not call {@link #invalidate()}.
10297     * </p>
10298     *
10299     * <p>
10300     * This method should be invoked everytime a subclass directly updates the
10301     * scroll parameters.
10302     * </p>
10303     *
10304     * @param startDelay the delay, in milliseconds, after which the animation
10305     *        should start; when the delay is 0, the animation starts
10306     *        immediately
10307     * @return true if the animation is played, false otherwise
10308     *
10309     * @see #scrollBy(int, int)
10310     * @see #scrollTo(int, int)
10311     * @see #isHorizontalScrollBarEnabled()
10312     * @see #isVerticalScrollBarEnabled()
10313     * @see #setHorizontalScrollBarEnabled(boolean)
10314     * @see #setVerticalScrollBarEnabled(boolean)
10315     */
10316    protected boolean awakenScrollBars(int startDelay) {
10317        return awakenScrollBars(startDelay, true);
10318    }
10319
10320    /**
10321     * <p>
10322     * Trigger the scrollbars to draw. When invoked this method starts an
10323     * animation to fade the scrollbars out after a fixed delay. If a subclass
10324     * provides animated scrolling, the start delay should equal the duration of
10325     * the scrolling animation.
10326     * </p>
10327     *
10328     * <p>
10329     * The animation starts only if at least one of the scrollbars is enabled,
10330     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10331     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10332     * this method returns true, and false otherwise. If the animation is
10333     * started, this method calls {@link #invalidate()} if the invalidate parameter
10334     * is set to true; in that case the caller
10335     * should not call {@link #invalidate()}.
10336     * </p>
10337     *
10338     * <p>
10339     * This method should be invoked everytime a subclass directly updates the
10340     * scroll parameters.
10341     * </p>
10342     *
10343     * @param startDelay the delay, in milliseconds, after which the animation
10344     *        should start; when the delay is 0, the animation starts
10345     *        immediately
10346     *
10347     * @param invalidate Wheter this method should call invalidate
10348     *
10349     * @return true if the animation is played, false otherwise
10350     *
10351     * @see #scrollBy(int, int)
10352     * @see #scrollTo(int, int)
10353     * @see #isHorizontalScrollBarEnabled()
10354     * @see #isVerticalScrollBarEnabled()
10355     * @see #setHorizontalScrollBarEnabled(boolean)
10356     * @see #setVerticalScrollBarEnabled(boolean)
10357     */
10358    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10359        final ScrollabilityCache scrollCache = mScrollCache;
10360
10361        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10362            return false;
10363        }
10364
10365        if (scrollCache.scrollBar == null) {
10366            scrollCache.scrollBar = new ScrollBarDrawable();
10367        }
10368
10369        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10370
10371            if (invalidate) {
10372                // Invalidate to show the scrollbars
10373                postInvalidateOnAnimation();
10374            }
10375
10376            if (scrollCache.state == ScrollabilityCache.OFF) {
10377                // FIXME: this is copied from WindowManagerService.
10378                // We should get this value from the system when it
10379                // is possible to do so.
10380                final int KEY_REPEAT_FIRST_DELAY = 750;
10381                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10382            }
10383
10384            // Tell mScrollCache when we should start fading. This may
10385            // extend the fade start time if one was already scheduled
10386            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10387            scrollCache.fadeStartTime = fadeStartTime;
10388            scrollCache.state = ScrollabilityCache.ON;
10389
10390            // Schedule our fader to run, unscheduling any old ones first
10391            if (mAttachInfo != null) {
10392                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10393                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10394            }
10395
10396            return true;
10397        }
10398
10399        return false;
10400    }
10401
10402    /**
10403     * Do not invalidate views which are not visible and which are not running an animation. They
10404     * will not get drawn and they should not set dirty flags as if they will be drawn
10405     */
10406    private boolean skipInvalidate() {
10407        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10408                (!(mParent instanceof ViewGroup) ||
10409                        !((ViewGroup) mParent).isViewTransitioning(this));
10410    }
10411    /**
10412     * Mark the area defined by dirty as needing to be drawn. If the view is
10413     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10414     * in the future. This must be called from a UI thread. To call from a non-UI
10415     * thread, call {@link #postInvalidate()}.
10416     *
10417     * WARNING: This method is destructive to dirty.
10418     * @param dirty the rectangle representing the bounds of the dirty region
10419     */
10420    public void invalidate(Rect dirty) {
10421        if (skipInvalidate()) {
10422            return;
10423        }
10424        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10425                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10426                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10427            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10428            mPrivateFlags |= PFLAG_INVALIDATED;
10429            mPrivateFlags |= PFLAG_DIRTY;
10430            final ViewParent p = mParent;
10431            final AttachInfo ai = mAttachInfo;
10432            //noinspection PointlessBooleanExpression,ConstantConditions
10433            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10434                if (p != null && ai != null && ai.mHardwareAccelerated) {
10435                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10436                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10437                    p.invalidateChild(this, null);
10438                    return;
10439                }
10440            }
10441            if (p != null && ai != null) {
10442                final int scrollX = mScrollX;
10443                final int scrollY = mScrollY;
10444                final Rect r = ai.mTmpInvalRect;
10445                r.set(dirty.left - scrollX, dirty.top - scrollY,
10446                        dirty.right - scrollX, dirty.bottom - scrollY);
10447                mParent.invalidateChild(this, r);
10448            }
10449        }
10450    }
10451
10452    /**
10453     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10454     * The coordinates of the dirty rect are relative to the view.
10455     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10456     * will be called at some point in the future. This must be called from
10457     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10458     * @param l the left position of the dirty region
10459     * @param t the top position of the dirty region
10460     * @param r the right position of the dirty region
10461     * @param b the bottom position of the dirty region
10462     */
10463    public void invalidate(int l, int t, int r, int b) {
10464        if (skipInvalidate()) {
10465            return;
10466        }
10467        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10468                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10469                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10470            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10471            mPrivateFlags |= PFLAG_INVALIDATED;
10472            mPrivateFlags |= PFLAG_DIRTY;
10473            final ViewParent p = mParent;
10474            final AttachInfo ai = mAttachInfo;
10475            //noinspection PointlessBooleanExpression,ConstantConditions
10476            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10477                if (p != null && ai != null && ai.mHardwareAccelerated) {
10478                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10479                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10480                    p.invalidateChild(this, null);
10481                    return;
10482                }
10483            }
10484            if (p != null && ai != null && l < r && t < b) {
10485                final int scrollX = mScrollX;
10486                final int scrollY = mScrollY;
10487                final Rect tmpr = ai.mTmpInvalRect;
10488                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10489                p.invalidateChild(this, tmpr);
10490            }
10491        }
10492    }
10493
10494    /**
10495     * Invalidate the whole view. If the view is visible,
10496     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10497     * the future. This must be called from a UI thread. To call from a non-UI thread,
10498     * call {@link #postInvalidate()}.
10499     */
10500    public void invalidate() {
10501        invalidate(true);
10502    }
10503
10504    /**
10505     * This is where the invalidate() work actually happens. A full invalidate()
10506     * causes the drawing cache to be invalidated, but this function can be called with
10507     * invalidateCache set to false to skip that invalidation step for cases that do not
10508     * need it (for example, a component that remains at the same dimensions with the same
10509     * content).
10510     *
10511     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10512     * well. This is usually true for a full invalidate, but may be set to false if the
10513     * View's contents or dimensions have not changed.
10514     */
10515    void invalidate(boolean invalidateCache) {
10516        if (skipInvalidate()) {
10517            return;
10518        }
10519        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10520                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10521                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10522            mLastIsOpaque = isOpaque();
10523            mPrivateFlags &= ~PFLAG_DRAWN;
10524            mPrivateFlags |= PFLAG_DIRTY;
10525            if (invalidateCache) {
10526                mPrivateFlags |= PFLAG_INVALIDATED;
10527                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10528            }
10529            final AttachInfo ai = mAttachInfo;
10530            final ViewParent p = mParent;
10531            //noinspection PointlessBooleanExpression,ConstantConditions
10532            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10533                if (p != null && ai != null && ai.mHardwareAccelerated) {
10534                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10535                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10536                    p.invalidateChild(this, null);
10537                    return;
10538                }
10539            }
10540
10541            if (p != null && ai != null) {
10542                final Rect r = ai.mTmpInvalRect;
10543                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10544                // Don't call invalidate -- we don't want to internally scroll
10545                // our own bounds
10546                p.invalidateChild(this, r);
10547            }
10548        }
10549    }
10550
10551    /**
10552     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10553     * set any flags or handle all of the cases handled by the default invalidation methods.
10554     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10555     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10556     * walk up the hierarchy, transforming the dirty rect as necessary.
10557     *
10558     * The method also handles normal invalidation logic if display list properties are not
10559     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10560     * backup approach, to handle these cases used in the various property-setting methods.
10561     *
10562     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10563     * are not being used in this view
10564     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10565     * list properties are not being used in this view
10566     */
10567    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10568        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10569            if (invalidateParent) {
10570                invalidateParentCaches();
10571            }
10572            if (forceRedraw) {
10573                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10574            }
10575            invalidate(false);
10576        } else {
10577            final AttachInfo ai = mAttachInfo;
10578            final ViewParent p = mParent;
10579            if (p != null && ai != null) {
10580                final Rect r = ai.mTmpInvalRect;
10581                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10582                if (mParent instanceof ViewGroup) {
10583                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10584                } else {
10585                    mParent.invalidateChild(this, r);
10586                }
10587            }
10588        }
10589    }
10590
10591    /**
10592     * Utility method to transform a given Rect by the current matrix of this view.
10593     */
10594    void transformRect(final Rect rect) {
10595        if (!getMatrix().isIdentity()) {
10596            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10597            boundingRect.set(rect);
10598            getMatrix().mapRect(boundingRect);
10599            rect.set((int) (boundingRect.left - 0.5f),
10600                    (int) (boundingRect.top - 0.5f),
10601                    (int) (boundingRect.right + 0.5f),
10602                    (int) (boundingRect.bottom + 0.5f));
10603        }
10604    }
10605
10606    /**
10607     * Used to indicate that the parent of this view should clear its caches. This functionality
10608     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10609     * which is necessary when various parent-managed properties of the view change, such as
10610     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10611     * clears the parent caches and does not causes an invalidate event.
10612     *
10613     * @hide
10614     */
10615    protected void invalidateParentCaches() {
10616        if (mParent instanceof View) {
10617            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10618        }
10619    }
10620
10621    /**
10622     * Used to indicate that the parent of this view should be invalidated. This functionality
10623     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10624     * which is necessary when various parent-managed properties of the view change, such as
10625     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10626     * an invalidation event to the parent.
10627     *
10628     * @hide
10629     */
10630    protected void invalidateParentIfNeeded() {
10631        if (isHardwareAccelerated() && mParent instanceof View) {
10632            ((View) mParent).invalidate(true);
10633        }
10634    }
10635
10636    /**
10637     * Indicates whether this View is opaque. An opaque View guarantees that it will
10638     * draw all the pixels overlapping its bounds using a fully opaque color.
10639     *
10640     * Subclasses of View should override this method whenever possible to indicate
10641     * whether an instance is opaque. Opaque Views are treated in a special way by
10642     * the View hierarchy, possibly allowing it to perform optimizations during
10643     * invalidate/draw passes.
10644     *
10645     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10646     */
10647    @ViewDebug.ExportedProperty(category = "drawing")
10648    public boolean isOpaque() {
10649        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10650                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10651    }
10652
10653    /**
10654     * @hide
10655     */
10656    protected void computeOpaqueFlags() {
10657        // Opaque if:
10658        //   - Has a background
10659        //   - Background is opaque
10660        //   - Doesn't have scrollbars or scrollbars overlay
10661
10662        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10663            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10664        } else {
10665            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10666        }
10667
10668        final int flags = mViewFlags;
10669        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10670                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY ||
10671                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) {
10672            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10673        } else {
10674            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10675        }
10676    }
10677
10678    /**
10679     * @hide
10680     */
10681    protected boolean hasOpaqueScrollbars() {
10682        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10683    }
10684
10685    /**
10686     * @return A handler associated with the thread running the View. This
10687     * handler can be used to pump events in the UI events queue.
10688     */
10689    public Handler getHandler() {
10690        if (mAttachInfo != null) {
10691            return mAttachInfo.mHandler;
10692        }
10693        return null;
10694    }
10695
10696    /**
10697     * Gets the view root associated with the View.
10698     * @return The view root, or null if none.
10699     * @hide
10700     */
10701    public ViewRootImpl getViewRootImpl() {
10702        if (mAttachInfo != null) {
10703            return mAttachInfo.mViewRootImpl;
10704        }
10705        return null;
10706    }
10707
10708    /**
10709     * <p>Causes the Runnable to be added to the message queue.
10710     * The runnable will be run on the user interface thread.</p>
10711     *
10712     * @param action The Runnable that will be executed.
10713     *
10714     * @return Returns true if the Runnable was successfully placed in to the
10715     *         message queue.  Returns false on failure, usually because the
10716     *         looper processing the message queue is exiting.
10717     *
10718     * @see #postDelayed
10719     * @see #removeCallbacks
10720     */
10721    public boolean post(Runnable action) {
10722        final AttachInfo attachInfo = mAttachInfo;
10723        if (attachInfo != null) {
10724            return attachInfo.mHandler.post(action);
10725        }
10726        // Assume that post will succeed later
10727        ViewRootImpl.getRunQueue().post(action);
10728        return true;
10729    }
10730
10731    /**
10732     * <p>Causes the Runnable to be added to the message queue, to be run
10733     * after the specified amount of time elapses.
10734     * The runnable will be run on the user interface thread.</p>
10735     *
10736     * @param action The Runnable that will be executed.
10737     * @param delayMillis The delay (in milliseconds) until the Runnable
10738     *        will be executed.
10739     *
10740     * @return true if the Runnable was successfully placed in to the
10741     *         message queue.  Returns false on failure, usually because the
10742     *         looper processing the message queue is exiting.  Note that a
10743     *         result of true does not mean the Runnable will be processed --
10744     *         if the looper is quit before the delivery time of the message
10745     *         occurs then the message will be dropped.
10746     *
10747     * @see #post
10748     * @see #removeCallbacks
10749     */
10750    public boolean postDelayed(Runnable action, long delayMillis) {
10751        final AttachInfo attachInfo = mAttachInfo;
10752        if (attachInfo != null) {
10753            return attachInfo.mHandler.postDelayed(action, delayMillis);
10754        }
10755        // Assume that post will succeed later
10756        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10757        return true;
10758    }
10759
10760    /**
10761     * <p>Causes the Runnable to execute on the next animation time step.
10762     * The runnable will be run on the user interface thread.</p>
10763     *
10764     * @param action The Runnable that will be executed.
10765     *
10766     * @see #postOnAnimationDelayed
10767     * @see #removeCallbacks
10768     */
10769    public void postOnAnimation(Runnable action) {
10770        final AttachInfo attachInfo = mAttachInfo;
10771        if (attachInfo != null) {
10772            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10773                    Choreographer.CALLBACK_ANIMATION, action, null);
10774        } else {
10775            // Assume that post will succeed later
10776            ViewRootImpl.getRunQueue().post(action);
10777        }
10778    }
10779
10780    /**
10781     * <p>Causes the Runnable to execute on the next animation time step,
10782     * after the specified amount of time elapses.
10783     * The runnable will be run on the user interface thread.</p>
10784     *
10785     * @param action The Runnable that will be executed.
10786     * @param delayMillis The delay (in milliseconds) until the Runnable
10787     *        will be executed.
10788     *
10789     * @see #postOnAnimation
10790     * @see #removeCallbacks
10791     */
10792    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10793        final AttachInfo attachInfo = mAttachInfo;
10794        if (attachInfo != null) {
10795            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10796                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10797        } else {
10798            // Assume that post will succeed later
10799            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10800        }
10801    }
10802
10803    /**
10804     * <p>Removes the specified Runnable from the message queue.</p>
10805     *
10806     * @param action The Runnable to remove from the message handling queue
10807     *
10808     * @return true if this view could ask the Handler to remove the Runnable,
10809     *         false otherwise. When the returned value is true, the Runnable
10810     *         may or may not have been actually removed from the message queue
10811     *         (for instance, if the Runnable was not in the queue already.)
10812     *
10813     * @see #post
10814     * @see #postDelayed
10815     * @see #postOnAnimation
10816     * @see #postOnAnimationDelayed
10817     */
10818    public boolean removeCallbacks(Runnable action) {
10819        if (action != null) {
10820            final AttachInfo attachInfo = mAttachInfo;
10821            if (attachInfo != null) {
10822                attachInfo.mHandler.removeCallbacks(action);
10823                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10824                        Choreographer.CALLBACK_ANIMATION, action, null);
10825            } else {
10826                // Assume that post will succeed later
10827                ViewRootImpl.getRunQueue().removeCallbacks(action);
10828            }
10829        }
10830        return true;
10831    }
10832
10833    /**
10834     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10835     * Use this to invalidate the View from a non-UI thread.</p>
10836     *
10837     * <p>This method can be invoked from outside of the UI thread
10838     * only when this View is attached to a window.</p>
10839     *
10840     * @see #invalidate()
10841     * @see #postInvalidateDelayed(long)
10842     */
10843    public void postInvalidate() {
10844        postInvalidateDelayed(0);
10845    }
10846
10847    /**
10848     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10849     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10850     *
10851     * <p>This method can be invoked from outside of the UI thread
10852     * only when this View is attached to a window.</p>
10853     *
10854     * @param left The left coordinate of the rectangle to invalidate.
10855     * @param top The top coordinate of the rectangle to invalidate.
10856     * @param right The right coordinate of the rectangle to invalidate.
10857     * @param bottom The bottom coordinate of the rectangle to invalidate.
10858     *
10859     * @see #invalidate(int, int, int, int)
10860     * @see #invalidate(Rect)
10861     * @see #postInvalidateDelayed(long, int, int, int, int)
10862     */
10863    public void postInvalidate(int left, int top, int right, int bottom) {
10864        postInvalidateDelayed(0, left, top, right, bottom);
10865    }
10866
10867    /**
10868     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10869     * loop. Waits for the specified amount of time.</p>
10870     *
10871     * <p>This method can be invoked from outside of the UI thread
10872     * only when this View is attached to a window.</p>
10873     *
10874     * @param delayMilliseconds the duration in milliseconds to delay the
10875     *         invalidation by
10876     *
10877     * @see #invalidate()
10878     * @see #postInvalidate()
10879     */
10880    public void postInvalidateDelayed(long delayMilliseconds) {
10881        // We try only with the AttachInfo because there's no point in invalidating
10882        // if we are not attached to our window
10883        final AttachInfo attachInfo = mAttachInfo;
10884        if (attachInfo != null) {
10885            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10886        }
10887    }
10888
10889    /**
10890     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10891     * through the event loop. Waits for the specified amount of time.</p>
10892     *
10893     * <p>This method can be invoked from outside of the UI thread
10894     * only when this View is attached to a window.</p>
10895     *
10896     * @param delayMilliseconds the duration in milliseconds to delay the
10897     *         invalidation by
10898     * @param left The left coordinate of the rectangle to invalidate.
10899     * @param top The top coordinate of the rectangle to invalidate.
10900     * @param right The right coordinate of the rectangle to invalidate.
10901     * @param bottom The bottom coordinate of the rectangle to invalidate.
10902     *
10903     * @see #invalidate(int, int, int, int)
10904     * @see #invalidate(Rect)
10905     * @see #postInvalidate(int, int, int, int)
10906     */
10907    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10908            int right, int bottom) {
10909
10910        // We try only with the AttachInfo because there's no point in invalidating
10911        // if we are not attached to our window
10912        final AttachInfo attachInfo = mAttachInfo;
10913        if (attachInfo != null) {
10914            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10915            info.target = this;
10916            info.left = left;
10917            info.top = top;
10918            info.right = right;
10919            info.bottom = bottom;
10920
10921            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10922        }
10923    }
10924
10925    /**
10926     * <p>Cause an invalidate to happen on the next animation time step, typically the
10927     * next display frame.</p>
10928     *
10929     * <p>This method can be invoked from outside of the UI thread
10930     * only when this View is attached to a window.</p>
10931     *
10932     * @see #invalidate()
10933     */
10934    public void postInvalidateOnAnimation() {
10935        // We try only with the AttachInfo because there's no point in invalidating
10936        // if we are not attached to our window
10937        final AttachInfo attachInfo = mAttachInfo;
10938        if (attachInfo != null) {
10939            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10940        }
10941    }
10942
10943    /**
10944     * <p>Cause an invalidate of the specified area to happen on the next animation
10945     * time step, typically the next display frame.</p>
10946     *
10947     * <p>This method can be invoked from outside of the UI thread
10948     * only when this View is attached to a window.</p>
10949     *
10950     * @param left The left coordinate of the rectangle to invalidate.
10951     * @param top The top coordinate of the rectangle to invalidate.
10952     * @param right The right coordinate of the rectangle to invalidate.
10953     * @param bottom The bottom coordinate of the rectangle to invalidate.
10954     *
10955     * @see #invalidate(int, int, int, int)
10956     * @see #invalidate(Rect)
10957     */
10958    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10959        // We try only with the AttachInfo because there's no point in invalidating
10960        // if we are not attached to our window
10961        final AttachInfo attachInfo = mAttachInfo;
10962        if (attachInfo != null) {
10963            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10964            info.target = this;
10965            info.left = left;
10966            info.top = top;
10967            info.right = right;
10968            info.bottom = bottom;
10969
10970            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10971        }
10972    }
10973
10974    /**
10975     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10976     * This event is sent at most once every
10977     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10978     */
10979    private void postSendViewScrolledAccessibilityEventCallback() {
10980        if (mSendViewScrolledAccessibilityEvent == null) {
10981            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10982        }
10983        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10984            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10985            postDelayed(mSendViewScrolledAccessibilityEvent,
10986                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10987        }
10988    }
10989
10990    /**
10991     * Called by a parent to request that a child update its values for mScrollX
10992     * and mScrollY if necessary. This will typically be done if the child is
10993     * animating a scroll using a {@link android.widget.Scroller Scroller}
10994     * object.
10995     */
10996    public void computeScroll() {
10997    }
10998
10999    /**
11000     * <p>Indicate whether the horizontal edges are faded when the view is
11001     * scrolled horizontally.</p>
11002     *
11003     * @return true if the horizontal edges should are faded on scroll, false
11004     *         otherwise
11005     *
11006     * @see #setHorizontalFadingEdgeEnabled(boolean)
11007     *
11008     * @attr ref android.R.styleable#View_requiresFadingEdge
11009     */
11010    public boolean isHorizontalFadingEdgeEnabled() {
11011        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
11012    }
11013
11014    /**
11015     * <p>Define whether the horizontal edges should be faded when this view
11016     * is scrolled horizontally.</p>
11017     *
11018     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11019     *                                    be faded when the view is scrolled
11020     *                                    horizontally
11021     *
11022     * @see #isHorizontalFadingEdgeEnabled()
11023     *
11024     * @attr ref android.R.styleable#View_requiresFadingEdge
11025     */
11026    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11027        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11028            if (horizontalFadingEdgeEnabled) {
11029                initScrollCache();
11030            }
11031
11032            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11033        }
11034    }
11035
11036    /**
11037     * <p>Indicate whether the vertical edges are faded when the view is
11038     * scrolled horizontally.</p>
11039     *
11040     * @return true if the vertical edges should are faded on scroll, false
11041     *         otherwise
11042     *
11043     * @see #setVerticalFadingEdgeEnabled(boolean)
11044     *
11045     * @attr ref android.R.styleable#View_requiresFadingEdge
11046     */
11047    public boolean isVerticalFadingEdgeEnabled() {
11048        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11049    }
11050
11051    /**
11052     * <p>Define whether the vertical edges should be faded when this view
11053     * is scrolled vertically.</p>
11054     *
11055     * @param verticalFadingEdgeEnabled true if the vertical edges should
11056     *                                  be faded when the view is scrolled
11057     *                                  vertically
11058     *
11059     * @see #isVerticalFadingEdgeEnabled()
11060     *
11061     * @attr ref android.R.styleable#View_requiresFadingEdge
11062     */
11063    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11064        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11065            if (verticalFadingEdgeEnabled) {
11066                initScrollCache();
11067            }
11068
11069            mViewFlags ^= FADING_EDGE_VERTICAL;
11070        }
11071    }
11072
11073    /**
11074     * Returns the strength, or intensity, of the top faded edge. The strength is
11075     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11076     * returns 0.0 or 1.0 but no value in between.
11077     *
11078     * Subclasses should override this method to provide a smoother fade transition
11079     * when scrolling occurs.
11080     *
11081     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11082     */
11083    protected float getTopFadingEdgeStrength() {
11084        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11085    }
11086
11087    /**
11088     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11089     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11090     * returns 0.0 or 1.0 but no value in between.
11091     *
11092     * Subclasses should override this method to provide a smoother fade transition
11093     * when scrolling occurs.
11094     *
11095     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11096     */
11097    protected float getBottomFadingEdgeStrength() {
11098        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11099                computeVerticalScrollRange() ? 1.0f : 0.0f;
11100    }
11101
11102    /**
11103     * Returns the strength, or intensity, of the left faded edge. The strength is
11104     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11105     * returns 0.0 or 1.0 but no value in between.
11106     *
11107     * Subclasses should override this method to provide a smoother fade transition
11108     * when scrolling occurs.
11109     *
11110     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11111     */
11112    protected float getLeftFadingEdgeStrength() {
11113        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11114    }
11115
11116    /**
11117     * Returns the strength, or intensity, of the right faded edge. The strength is
11118     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11119     * returns 0.0 or 1.0 but no value in between.
11120     *
11121     * Subclasses should override this method to provide a smoother fade transition
11122     * when scrolling occurs.
11123     *
11124     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11125     */
11126    protected float getRightFadingEdgeStrength() {
11127        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11128                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11129    }
11130
11131    /**
11132     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11133     * scrollbar is not drawn by default.</p>
11134     *
11135     * @return true if the horizontal scrollbar should be painted, false
11136     *         otherwise
11137     *
11138     * @see #setHorizontalScrollBarEnabled(boolean)
11139     */
11140    public boolean isHorizontalScrollBarEnabled() {
11141        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11142    }
11143
11144    /**
11145     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11146     * scrollbar is not drawn by default.</p>
11147     *
11148     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11149     *                                   be painted
11150     *
11151     * @see #isHorizontalScrollBarEnabled()
11152     */
11153    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11154        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11155            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11156            computeOpaqueFlags();
11157            resolvePadding();
11158        }
11159    }
11160
11161    /**
11162     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11163     * scrollbar is not drawn by default.</p>
11164     *
11165     * @return true if the vertical scrollbar should be painted, false
11166     *         otherwise
11167     *
11168     * @see #setVerticalScrollBarEnabled(boolean)
11169     */
11170    public boolean isVerticalScrollBarEnabled() {
11171        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11172    }
11173
11174    /**
11175     * <p>Define whether the vertical scrollbar should be drawn or not. The
11176     * scrollbar is not drawn by default.</p>
11177     *
11178     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11179     *                                 be painted
11180     *
11181     * @see #isVerticalScrollBarEnabled()
11182     */
11183    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11184        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11185            mViewFlags ^= SCROLLBARS_VERTICAL;
11186            computeOpaqueFlags();
11187            resolvePadding();
11188        }
11189    }
11190
11191    /**
11192     * @hide
11193     */
11194    protected void recomputePadding() {
11195        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11196    }
11197
11198    /**
11199     * Define whether scrollbars will fade when the view is not scrolling.
11200     *
11201     * @param fadeScrollbars wheter to enable fading
11202     *
11203     * @attr ref android.R.styleable#View_fadeScrollbars
11204     */
11205    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11206        initScrollCache();
11207        final ScrollabilityCache scrollabilityCache = mScrollCache;
11208        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11209        if (fadeScrollbars) {
11210            scrollabilityCache.state = ScrollabilityCache.OFF;
11211        } else {
11212            scrollabilityCache.state = ScrollabilityCache.ON;
11213        }
11214    }
11215
11216    /**
11217     *
11218     * Returns true if scrollbars will fade when this view is not scrolling
11219     *
11220     * @return true if scrollbar fading is enabled
11221     *
11222     * @attr ref android.R.styleable#View_fadeScrollbars
11223     */
11224    public boolean isScrollbarFadingEnabled() {
11225        return mScrollCache != null && mScrollCache.fadeScrollBars;
11226    }
11227
11228    /**
11229     *
11230     * Returns the delay before scrollbars fade.
11231     *
11232     * @return the delay before scrollbars fade
11233     *
11234     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11235     */
11236    public int getScrollBarDefaultDelayBeforeFade() {
11237        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11238                mScrollCache.scrollBarDefaultDelayBeforeFade;
11239    }
11240
11241    /**
11242     * Define the delay before scrollbars fade.
11243     *
11244     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11245     *
11246     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11247     */
11248    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11249        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11250    }
11251
11252    /**
11253     *
11254     * Returns the scrollbar fade duration.
11255     *
11256     * @return the scrollbar fade duration
11257     *
11258     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11259     */
11260    public int getScrollBarFadeDuration() {
11261        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11262                mScrollCache.scrollBarFadeDuration;
11263    }
11264
11265    /**
11266     * Define the scrollbar fade duration.
11267     *
11268     * @param scrollBarFadeDuration - the scrollbar fade duration
11269     *
11270     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11271     */
11272    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11273        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11274    }
11275
11276    /**
11277     *
11278     * Returns the scrollbar size.
11279     *
11280     * @return the scrollbar size
11281     *
11282     * @attr ref android.R.styleable#View_scrollbarSize
11283     */
11284    public int getScrollBarSize() {
11285        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11286                mScrollCache.scrollBarSize;
11287    }
11288
11289    /**
11290     * Define the scrollbar size.
11291     *
11292     * @param scrollBarSize - the scrollbar size
11293     *
11294     * @attr ref android.R.styleable#View_scrollbarSize
11295     */
11296    public void setScrollBarSize(int scrollBarSize) {
11297        getScrollCache().scrollBarSize = scrollBarSize;
11298    }
11299
11300    /**
11301     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11302     * inset. When inset, they add to the padding of the view. And the scrollbars
11303     * can be drawn inside the padding area or on the edge of the view. For example,
11304     * if a view has a background drawable and you want to draw the scrollbars
11305     * inside the padding specified by the drawable, you can use
11306     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11307     * appear at the edge of the view, ignoring the padding, then you can use
11308     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11309     * @param style the style of the scrollbars. Should be one of
11310     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11311     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11312     * @see #SCROLLBARS_INSIDE_OVERLAY
11313     * @see #SCROLLBARS_INSIDE_INSET
11314     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11315     * @see #SCROLLBARS_OUTSIDE_INSET
11316     *
11317     * @attr ref android.R.styleable#View_scrollbarStyle
11318     */
11319    public void setScrollBarStyle(int style) {
11320        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11321            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11322            computeOpaqueFlags();
11323            resolvePadding();
11324        }
11325    }
11326
11327    /**
11328     * <p>Returns the current scrollbar style.</p>
11329     * @return the current scrollbar style
11330     * @see #SCROLLBARS_INSIDE_OVERLAY
11331     * @see #SCROLLBARS_INSIDE_INSET
11332     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11333     * @see #SCROLLBARS_OUTSIDE_INSET
11334     *
11335     * @attr ref android.R.styleable#View_scrollbarStyle
11336     */
11337    @ViewDebug.ExportedProperty(mapping = {
11338            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11339            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11340            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11341            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11342    })
11343    public int getScrollBarStyle() {
11344        return mViewFlags & SCROLLBARS_STYLE_MASK;
11345    }
11346
11347    /**
11348     * <p>Compute the horizontal range that the horizontal scrollbar
11349     * represents.</p>
11350     *
11351     * <p>The range is expressed in arbitrary units that must be the same as the
11352     * units used by {@link #computeHorizontalScrollExtent()} and
11353     * {@link #computeHorizontalScrollOffset()}.</p>
11354     *
11355     * <p>The default range is the drawing width of this view.</p>
11356     *
11357     * @return the total horizontal range represented by the horizontal
11358     *         scrollbar
11359     *
11360     * @see #computeHorizontalScrollExtent()
11361     * @see #computeHorizontalScrollOffset()
11362     * @see android.widget.ScrollBarDrawable
11363     */
11364    protected int computeHorizontalScrollRange() {
11365        return getWidth();
11366    }
11367
11368    /**
11369     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11370     * within the horizontal range. This value is used to compute the position
11371     * of the thumb within the scrollbar's track.</p>
11372     *
11373     * <p>The range is expressed in arbitrary units that must be the same as the
11374     * units used by {@link #computeHorizontalScrollRange()} and
11375     * {@link #computeHorizontalScrollExtent()}.</p>
11376     *
11377     * <p>The default offset is the scroll offset of this view.</p>
11378     *
11379     * @return the horizontal offset of the scrollbar's thumb
11380     *
11381     * @see #computeHorizontalScrollRange()
11382     * @see #computeHorizontalScrollExtent()
11383     * @see android.widget.ScrollBarDrawable
11384     */
11385    protected int computeHorizontalScrollOffset() {
11386        return mScrollX;
11387    }
11388
11389    /**
11390     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11391     * within the horizontal range. This value is used to compute the length
11392     * of the thumb within the scrollbar's track.</p>
11393     *
11394     * <p>The range is expressed in arbitrary units that must be the same as the
11395     * units used by {@link #computeHorizontalScrollRange()} and
11396     * {@link #computeHorizontalScrollOffset()}.</p>
11397     *
11398     * <p>The default extent is the drawing width of this view.</p>
11399     *
11400     * @return the horizontal extent of the scrollbar's thumb
11401     *
11402     * @see #computeHorizontalScrollRange()
11403     * @see #computeHorizontalScrollOffset()
11404     * @see android.widget.ScrollBarDrawable
11405     */
11406    protected int computeHorizontalScrollExtent() {
11407        return getWidth();
11408    }
11409
11410    /**
11411     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11412     *
11413     * <p>The range is expressed in arbitrary units that must be the same as the
11414     * units used by {@link #computeVerticalScrollExtent()} and
11415     * {@link #computeVerticalScrollOffset()}.</p>
11416     *
11417     * @return the total vertical range represented by the vertical scrollbar
11418     *
11419     * <p>The default range is the drawing height of this view.</p>
11420     *
11421     * @see #computeVerticalScrollExtent()
11422     * @see #computeVerticalScrollOffset()
11423     * @see android.widget.ScrollBarDrawable
11424     */
11425    protected int computeVerticalScrollRange() {
11426        return getHeight();
11427    }
11428
11429    /**
11430     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11431     * within the horizontal range. This value is used to compute the position
11432     * of the thumb within the scrollbar's track.</p>
11433     *
11434     * <p>The range is expressed in arbitrary units that must be the same as the
11435     * units used by {@link #computeVerticalScrollRange()} and
11436     * {@link #computeVerticalScrollExtent()}.</p>
11437     *
11438     * <p>The default offset is the scroll offset of this view.</p>
11439     *
11440     * @return the vertical offset of the scrollbar's thumb
11441     *
11442     * @see #computeVerticalScrollRange()
11443     * @see #computeVerticalScrollExtent()
11444     * @see android.widget.ScrollBarDrawable
11445     */
11446    protected int computeVerticalScrollOffset() {
11447        return mScrollY;
11448    }
11449
11450    /**
11451     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11452     * within the vertical range. This value is used to compute the length
11453     * of the thumb within the scrollbar's track.</p>
11454     *
11455     * <p>The range is expressed in arbitrary units that must be the same as the
11456     * units used by {@link #computeVerticalScrollRange()} and
11457     * {@link #computeVerticalScrollOffset()}.</p>
11458     *
11459     * <p>The default extent is the drawing height of this view.</p>
11460     *
11461     * @return the vertical extent of the scrollbar's thumb
11462     *
11463     * @see #computeVerticalScrollRange()
11464     * @see #computeVerticalScrollOffset()
11465     * @see android.widget.ScrollBarDrawable
11466     */
11467    protected int computeVerticalScrollExtent() {
11468        return getHeight();
11469    }
11470
11471    /**
11472     * Check if this view can be scrolled horizontally in a certain direction.
11473     *
11474     * @param direction Negative to check scrolling left, positive to check scrolling right.
11475     * @return true if this view can be scrolled in the specified direction, false otherwise.
11476     */
11477    public boolean canScrollHorizontally(int direction) {
11478        final int offset = computeHorizontalScrollOffset();
11479        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11480        if (range == 0) return false;
11481        if (direction < 0) {
11482            return offset > 0;
11483        } else {
11484            return offset < range - 1;
11485        }
11486    }
11487
11488    /**
11489     * Check if this view can be scrolled vertically in a certain direction.
11490     *
11491     * @param direction Negative to check scrolling up, positive to check scrolling down.
11492     * @return true if this view can be scrolled in the specified direction, false otherwise.
11493     */
11494    public boolean canScrollVertically(int direction) {
11495        final int offset = computeVerticalScrollOffset();
11496        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11497        if (range == 0) return false;
11498        if (direction < 0) {
11499            return offset > 0;
11500        } else {
11501            return offset < range - 1;
11502        }
11503    }
11504
11505    /**
11506     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11507     * scrollbars are painted only if they have been awakened first.</p>
11508     *
11509     * @param canvas the canvas on which to draw the scrollbars
11510     *
11511     * @see #awakenScrollBars(int)
11512     */
11513    protected final void onDrawScrollBars(Canvas canvas) {
11514        // scrollbars are drawn only when the animation is running
11515        final ScrollabilityCache cache = mScrollCache;
11516        if (cache != null) {
11517
11518            int state = cache.state;
11519
11520            if (state == ScrollabilityCache.OFF) {
11521                return;
11522            }
11523
11524            boolean invalidate = false;
11525
11526            if (state == ScrollabilityCache.FADING) {
11527                // We're fading -- get our fade interpolation
11528                if (cache.interpolatorValues == null) {
11529                    cache.interpolatorValues = new float[1];
11530                }
11531
11532                float[] values = cache.interpolatorValues;
11533
11534                // Stops the animation if we're done
11535                if (cache.scrollBarInterpolator.timeToValues(values) ==
11536                        Interpolator.Result.FREEZE_END) {
11537                    cache.state = ScrollabilityCache.OFF;
11538                } else {
11539                    cache.scrollBar.setAlpha(Math.round(values[0]));
11540                }
11541
11542                // This will make the scroll bars inval themselves after
11543                // drawing. We only want this when we're fading so that
11544                // we prevent excessive redraws
11545                invalidate = true;
11546            } else {
11547                // We're just on -- but we may have been fading before so
11548                // reset alpha
11549                cache.scrollBar.setAlpha(255);
11550            }
11551
11552
11553            final int viewFlags = mViewFlags;
11554
11555            final boolean drawHorizontalScrollBar =
11556                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11557            final boolean drawVerticalScrollBar =
11558                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11559                && !isVerticalScrollBarHidden();
11560
11561            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11562                final int width = mRight - mLeft;
11563                final int height = mBottom - mTop;
11564
11565                final ScrollBarDrawable scrollBar = cache.scrollBar;
11566
11567                final int scrollX = mScrollX;
11568                final int scrollY = mScrollY;
11569                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11570
11571                int left;
11572                int top;
11573                int right;
11574                int bottom;
11575
11576                if (drawHorizontalScrollBar) {
11577                    int size = scrollBar.getSize(false);
11578                    if (size <= 0) {
11579                        size = cache.scrollBarSize;
11580                    }
11581
11582                    scrollBar.setParameters(computeHorizontalScrollRange(),
11583                                            computeHorizontalScrollOffset(),
11584                                            computeHorizontalScrollExtent(), false);
11585                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11586                            getVerticalScrollbarWidth() : 0;
11587                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11588                    left = scrollX + (mPaddingLeft & inside);
11589                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11590                    bottom = top + size;
11591                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11592                    if (invalidate) {
11593                        invalidate(left, top, right, bottom);
11594                    }
11595                }
11596
11597                if (drawVerticalScrollBar) {
11598                    int size = scrollBar.getSize(true);
11599                    if (size <= 0) {
11600                        size = cache.scrollBarSize;
11601                    }
11602
11603                    scrollBar.setParameters(computeVerticalScrollRange(),
11604                                            computeVerticalScrollOffset(),
11605                                            computeVerticalScrollExtent(), true);
11606                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11607                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11608                        verticalScrollbarPosition = isLayoutRtl() ?
11609                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11610                    }
11611                    switch (verticalScrollbarPosition) {
11612                        default:
11613                        case SCROLLBAR_POSITION_RIGHT:
11614                            left = scrollX + width - size - (mUserPaddingRight & inside);
11615                            break;
11616                        case SCROLLBAR_POSITION_LEFT:
11617                            left = scrollX + (mUserPaddingLeft & inside);
11618                            break;
11619                    }
11620                    top = scrollY + (mPaddingTop & inside);
11621                    right = left + size;
11622                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11623                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11624                    if (invalidate) {
11625                        invalidate(left, top, right, bottom);
11626                    }
11627                }
11628            }
11629        }
11630    }
11631
11632    /**
11633     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11634     * FastScroller is visible.
11635     * @return whether to temporarily hide the vertical scrollbar
11636     * @hide
11637     */
11638    protected boolean isVerticalScrollBarHidden() {
11639        return false;
11640    }
11641
11642    /**
11643     * <p>Draw the horizontal scrollbar if
11644     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11645     *
11646     * @param canvas the canvas on which to draw the scrollbar
11647     * @param scrollBar the scrollbar's drawable
11648     *
11649     * @see #isHorizontalScrollBarEnabled()
11650     * @see #computeHorizontalScrollRange()
11651     * @see #computeHorizontalScrollExtent()
11652     * @see #computeHorizontalScrollOffset()
11653     * @see android.widget.ScrollBarDrawable
11654     * @hide
11655     */
11656    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11657            int l, int t, int r, int b) {
11658        scrollBar.setBounds(l, t, r, b);
11659        scrollBar.draw(canvas);
11660    }
11661
11662    /**
11663     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11664     * returns true.</p>
11665     *
11666     * @param canvas the canvas on which to draw the scrollbar
11667     * @param scrollBar the scrollbar's drawable
11668     *
11669     * @see #isVerticalScrollBarEnabled()
11670     * @see #computeVerticalScrollRange()
11671     * @see #computeVerticalScrollExtent()
11672     * @see #computeVerticalScrollOffset()
11673     * @see android.widget.ScrollBarDrawable
11674     * @hide
11675     */
11676    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11677            int l, int t, int r, int b) {
11678        scrollBar.setBounds(l, t, r, b);
11679        scrollBar.draw(canvas);
11680    }
11681
11682    /**
11683     * Implement this to do your drawing.
11684     *
11685     * @param canvas the canvas on which the background will be drawn
11686     */
11687    protected void onDraw(Canvas canvas) {
11688    }
11689
11690    /*
11691     * Caller is responsible for calling requestLayout if necessary.
11692     * (This allows addViewInLayout to not request a new layout.)
11693     */
11694    void assignParent(ViewParent parent) {
11695        if (mParent == null) {
11696            mParent = parent;
11697        } else if (parent == null) {
11698            mParent = null;
11699        } else {
11700            throw new RuntimeException("view " + this + " being added, but"
11701                    + " it already has a parent");
11702        }
11703    }
11704
11705    /**
11706     * This is called when the view is attached to a window.  At this point it
11707     * has a Surface and will start drawing.  Note that this function is
11708     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11709     * however it may be called any time before the first onDraw -- including
11710     * before or after {@link #onMeasure(int, int)}.
11711     *
11712     * @see #onDetachedFromWindow()
11713     */
11714    protected void onAttachedToWindow() {
11715        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11716            mParent.requestTransparentRegion(this);
11717        }
11718
11719        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11720            initialAwakenScrollBars();
11721            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11722        }
11723
11724        jumpDrawablesToCurrentState();
11725
11726        clearAccessibilityFocus();
11727        if (isFocused()) {
11728            InputMethodManager imm = InputMethodManager.peekInstance();
11729            imm.focusIn(this);
11730        }
11731
11732        if (mDisplayList != null) {
11733            mDisplayList.clearDirty();
11734        }
11735    }
11736
11737    /**
11738     * Resolve all RTL related properties.
11739     *
11740     * @hide
11741     */
11742    public void resolveRtlPropertiesIfNeeded() {
11743        if (!needRtlPropertiesResolution()) return;
11744
11745        // Order is important here: LayoutDirection MUST be resolved first
11746        if (!isLayoutDirectionResolved()) {
11747            resolveLayoutDirection();
11748            resolveLayoutParams();
11749        }
11750        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11751        if (!isTextDirectionResolved()) {
11752            resolveTextDirection();
11753        }
11754        if (!isTextAlignmentResolved()) {
11755            resolveTextAlignment();
11756        }
11757        if (!isPaddingResolved()) {
11758            resolvePadding();
11759        }
11760        if (!isDrawablesResolved()) {
11761            resolveDrawables();
11762        }
11763        onRtlPropertiesChanged(getLayoutDirection());
11764    }
11765
11766    /**
11767     * Reset resolution of all RTL related properties.
11768     *
11769     * @hide
11770     */
11771    public void resetRtlProperties() {
11772        resetResolvedLayoutDirection();
11773        resetResolvedTextDirection();
11774        resetResolvedTextAlignment();
11775        resetResolvedPadding();
11776        resetResolvedDrawables();
11777    }
11778
11779    /**
11780     * @see #onScreenStateChanged(int)
11781     */
11782    void dispatchScreenStateChanged(int screenState) {
11783        onScreenStateChanged(screenState);
11784    }
11785
11786    /**
11787     * This method is called whenever the state of the screen this view is
11788     * attached to changes. A state change will usually occurs when the screen
11789     * turns on or off (whether it happens automatically or the user does it
11790     * manually.)
11791     *
11792     * @param screenState The new state of the screen. Can be either
11793     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11794     */
11795    public void onScreenStateChanged(int screenState) {
11796    }
11797
11798    /**
11799     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11800     */
11801    private boolean hasRtlSupport() {
11802        return mContext.getApplicationInfo().hasRtlSupport();
11803    }
11804
11805    /**
11806     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11807     * RTL not supported)
11808     */
11809    private boolean isRtlCompatibilityMode() {
11810        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11811        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11812    }
11813
11814    /**
11815     * @return true if RTL properties need resolution.
11816     */
11817    private boolean needRtlPropertiesResolution() {
11818        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11819    }
11820
11821    /**
11822     * Called when any RTL property (layout direction or text direction or text alignment) has
11823     * been changed.
11824     *
11825     * Subclasses need to override this method to take care of cached information that depends on the
11826     * resolved layout direction, or to inform child views that inherit their layout direction.
11827     *
11828     * The default implementation does nothing.
11829     *
11830     * @param layoutDirection the direction of the layout
11831     *
11832     * @see #LAYOUT_DIRECTION_LTR
11833     * @see #LAYOUT_DIRECTION_RTL
11834     */
11835    public void onRtlPropertiesChanged(int layoutDirection) {
11836    }
11837
11838    /**
11839     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11840     * that the parent directionality can and will be resolved before its children.
11841     *
11842     * @return true if resolution has been done, false otherwise.
11843     *
11844     * @hide
11845     */
11846    public boolean resolveLayoutDirection() {
11847        // Clear any previous layout direction resolution
11848        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11849
11850        if (hasRtlSupport()) {
11851            // Set resolved depending on layout direction
11852            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11853                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11854                case LAYOUT_DIRECTION_INHERIT:
11855                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11856                    // later to get the correct resolved value
11857                    if (!canResolveLayoutDirection()) return false;
11858
11859                    // Parent has not yet resolved, LTR is still the default
11860                    if (!mParent.isLayoutDirectionResolved()) return false;
11861
11862                    if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11863                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11864                    }
11865                    break;
11866                case LAYOUT_DIRECTION_RTL:
11867                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11868                    break;
11869                case LAYOUT_DIRECTION_LOCALE:
11870                    if((LAYOUT_DIRECTION_RTL ==
11871                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11872                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11873                    }
11874                    break;
11875                default:
11876                    // Nothing to do, LTR by default
11877            }
11878        }
11879
11880        // Set to resolved
11881        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11882        return true;
11883    }
11884
11885    /**
11886     * Check if layout direction resolution can be done.
11887     *
11888     * @return true if layout direction resolution can be done otherwise return false.
11889     *
11890     * @hide
11891     */
11892    public boolean canResolveLayoutDirection() {
11893        switch (getRawLayoutDirection()) {
11894            case LAYOUT_DIRECTION_INHERIT:
11895                return (mParent != null) && mParent.canResolveLayoutDirection();
11896            default:
11897                return true;
11898        }
11899    }
11900
11901    /**
11902     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11903     * {@link #onMeasure(int, int)}.
11904     *
11905     * @hide
11906     */
11907    public void resetResolvedLayoutDirection() {
11908        // Reset the current resolved bits
11909        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11910    }
11911
11912    /**
11913     * @return true if the layout direction is inherited.
11914     *
11915     * @hide
11916     */
11917    public boolean isLayoutDirectionInherited() {
11918        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
11919    }
11920
11921    /**
11922     * @return true if layout direction has been resolved.
11923     * @hide
11924     */
11925    public boolean isLayoutDirectionResolved() {
11926        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11927    }
11928
11929    /**
11930     * Return if padding has been resolved
11931     *
11932     * @hide
11933     */
11934    boolean isPaddingResolved() {
11935        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
11936    }
11937
11938    /**
11939     * Resolve padding depending on layout direction.
11940     *
11941     * @hide
11942     */
11943    public void resolvePadding() {
11944        if (!isRtlCompatibilityMode()) {
11945            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11946            // If start / end padding are defined, they will be resolved (hence overriding) to
11947            // left / right or right / left depending on the resolved layout direction.
11948            // If start / end padding are not defined, use the left / right ones.
11949            int resolvedLayoutDirection = getLayoutDirection();
11950            // Set user padding to initial values ...
11951            mUserPaddingLeft = mUserPaddingLeftInitial;
11952            mUserPaddingRight = mUserPaddingRightInitial;
11953            // ... then resolve it.
11954            switch (resolvedLayoutDirection) {
11955                case LAYOUT_DIRECTION_RTL:
11956                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11957                        mUserPaddingRight = mUserPaddingStart;
11958                    }
11959                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11960                        mUserPaddingLeft = mUserPaddingEnd;
11961                    }
11962                    break;
11963                case LAYOUT_DIRECTION_LTR:
11964                default:
11965                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11966                        mUserPaddingLeft = mUserPaddingStart;
11967                    }
11968                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11969                        mUserPaddingRight = mUserPaddingEnd;
11970                    }
11971            }
11972
11973            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11974
11975            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11976                    mUserPaddingBottom);
11977            onRtlPropertiesChanged(resolvedLayoutDirection);
11978        }
11979
11980        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11981    }
11982
11983    /**
11984     * Reset the resolved layout direction.
11985     *
11986     * @hide
11987     */
11988    public void resetResolvedPadding() {
11989        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
11990    }
11991
11992    /**
11993     * This is called when the view is detached from a window.  At this point it
11994     * no longer has a surface for drawing.
11995     *
11996     * @see #onAttachedToWindow()
11997     */
11998    protected void onDetachedFromWindow() {
11999        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
12000
12001        removeUnsetPressCallback();
12002        removeLongPressCallback();
12003        removePerformClickCallback();
12004        removeSendViewScrolledAccessibilityEventCallback();
12005
12006        destroyDrawingCache();
12007
12008        destroyLayer(false);
12009
12010        if (mAttachInfo != null) {
12011            if (mDisplayList != null) {
12012                mDisplayList.markDirty();
12013                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
12014            }
12015            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
12016        } else {
12017            // Should never happen
12018            clearDisplayList();
12019        }
12020
12021        mCurrentAnimation = null;
12022
12023        resetAccessibilityStateChanged();
12024    }
12025
12026    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
12027    }
12028
12029    /**
12030     * @return The number of times this view has been attached to a window
12031     */
12032    protected int getWindowAttachCount() {
12033        return mWindowAttachCount;
12034    }
12035
12036    /**
12037     * Retrieve a unique token identifying the window this view is attached to.
12038     * @return Return the window's token for use in
12039     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12040     */
12041    public IBinder getWindowToken() {
12042        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12043    }
12044
12045    /**
12046     * Retrieve the {@link WindowId} for the window this view is
12047     * currently attached to.
12048     */
12049    public WindowId getWindowId() {
12050        if (mAttachInfo == null) {
12051            return null;
12052        }
12053        if (mAttachInfo.mWindowId == null) {
12054            try {
12055                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12056                        mAttachInfo.mWindowToken);
12057                mAttachInfo.mWindowId = new WindowId(
12058                        mAttachInfo.mIWindowId);
12059            } catch (RemoteException e) {
12060            }
12061        }
12062        return mAttachInfo.mWindowId;
12063    }
12064
12065    /**
12066     * Retrieve a unique token identifying the top-level "real" window of
12067     * the window that this view is attached to.  That is, this is like
12068     * {@link #getWindowToken}, except if the window this view in is a panel
12069     * window (attached to another containing window), then the token of
12070     * the containing window is returned instead.
12071     *
12072     * @return Returns the associated window token, either
12073     * {@link #getWindowToken()} or the containing window's token.
12074     */
12075    public IBinder getApplicationWindowToken() {
12076        AttachInfo ai = mAttachInfo;
12077        if (ai != null) {
12078            IBinder appWindowToken = ai.mPanelParentWindowToken;
12079            if (appWindowToken == null) {
12080                appWindowToken = ai.mWindowToken;
12081            }
12082            return appWindowToken;
12083        }
12084        return null;
12085    }
12086
12087    /**
12088     * Gets the logical display to which the view's window has been attached.
12089     *
12090     * @return The logical display, or null if the view is not currently attached to a window.
12091     */
12092    public Display getDisplay() {
12093        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12094    }
12095
12096    /**
12097     * Retrieve private session object this view hierarchy is using to
12098     * communicate with the window manager.
12099     * @return the session object to communicate with the window manager
12100     */
12101    /*package*/ IWindowSession getWindowSession() {
12102        return mAttachInfo != null ? mAttachInfo.mSession : null;
12103    }
12104
12105    /**
12106     * @param info the {@link android.view.View.AttachInfo} to associated with
12107     *        this view
12108     */
12109    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12110        //System.out.println("Attached! " + this);
12111        mAttachInfo = info;
12112        if (mOverlay != null) {
12113            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
12114        }
12115        mWindowAttachCount++;
12116        // We will need to evaluate the drawable state at least once.
12117        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12118        if (mFloatingTreeObserver != null) {
12119            info.mTreeObserver.merge(mFloatingTreeObserver);
12120            mFloatingTreeObserver = null;
12121        }
12122        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12123            mAttachInfo.mScrollContainers.add(this);
12124            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12125        }
12126        performCollectViewAttributes(mAttachInfo, visibility);
12127        onAttachedToWindow();
12128
12129        ListenerInfo li = mListenerInfo;
12130        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12131                li != null ? li.mOnAttachStateChangeListeners : null;
12132        if (listeners != null && listeners.size() > 0) {
12133            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12134            // perform the dispatching. The iterator is a safe guard against listeners that
12135            // could mutate the list by calling the various add/remove methods. This prevents
12136            // the array from being modified while we iterate it.
12137            for (OnAttachStateChangeListener listener : listeners) {
12138                listener.onViewAttachedToWindow(this);
12139            }
12140        }
12141
12142        int vis = info.mWindowVisibility;
12143        if (vis != GONE) {
12144            onWindowVisibilityChanged(vis);
12145        }
12146        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12147            // If nobody has evaluated the drawable state yet, then do it now.
12148            refreshDrawableState();
12149        }
12150        needGlobalAttributesUpdate(false);
12151    }
12152
12153    void dispatchDetachedFromWindow() {
12154        AttachInfo info = mAttachInfo;
12155        if (info != null) {
12156            int vis = info.mWindowVisibility;
12157            if (vis != GONE) {
12158                onWindowVisibilityChanged(GONE);
12159            }
12160        }
12161
12162        onDetachedFromWindow();
12163
12164        ListenerInfo li = mListenerInfo;
12165        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12166                li != null ? li.mOnAttachStateChangeListeners : null;
12167        if (listeners != null && listeners.size() > 0) {
12168            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12169            // perform the dispatching. The iterator is a safe guard against listeners that
12170            // could mutate the list by calling the various add/remove methods. This prevents
12171            // the array from being modified while we iterate it.
12172            for (OnAttachStateChangeListener listener : listeners) {
12173                listener.onViewDetachedFromWindow(this);
12174            }
12175        }
12176
12177        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12178            mAttachInfo.mScrollContainers.remove(this);
12179            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12180        }
12181
12182        mAttachInfo = null;
12183        if (mOverlay != null) {
12184            mOverlay.getOverlayView().dispatchDetachedFromWindow();
12185        }
12186    }
12187
12188    /**
12189     * Store this view hierarchy's frozen state into the given container.
12190     *
12191     * @param container The SparseArray in which to save the view's state.
12192     *
12193     * @see #restoreHierarchyState(android.util.SparseArray)
12194     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12195     * @see #onSaveInstanceState()
12196     */
12197    public void saveHierarchyState(SparseArray<Parcelable> container) {
12198        dispatchSaveInstanceState(container);
12199    }
12200
12201    /**
12202     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12203     * this view and its children. May be overridden to modify how freezing happens to a
12204     * view's children; for example, some views may want to not store state for their children.
12205     *
12206     * @param container The SparseArray in which to save the view's state.
12207     *
12208     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12209     * @see #saveHierarchyState(android.util.SparseArray)
12210     * @see #onSaveInstanceState()
12211     */
12212    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12213        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12214            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12215            Parcelable state = onSaveInstanceState();
12216            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12217                throw new IllegalStateException(
12218                        "Derived class did not call super.onSaveInstanceState()");
12219            }
12220            if (state != null) {
12221                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12222                // + ": " + state);
12223                container.put(mID, state);
12224            }
12225        }
12226    }
12227
12228    /**
12229     * Hook allowing a view to generate a representation of its internal state
12230     * that can later be used to create a new instance with that same state.
12231     * This state should only contain information that is not persistent or can
12232     * not be reconstructed later. For example, you will never store your
12233     * current position on screen because that will be computed again when a
12234     * new instance of the view is placed in its view hierarchy.
12235     * <p>
12236     * Some examples of things you may store here: the current cursor position
12237     * in a text view (but usually not the text itself since that is stored in a
12238     * content provider or other persistent storage), the currently selected
12239     * item in a list view.
12240     *
12241     * @return Returns a Parcelable object containing the view's current dynamic
12242     *         state, or null if there is nothing interesting to save. The
12243     *         default implementation returns null.
12244     * @see #onRestoreInstanceState(android.os.Parcelable)
12245     * @see #saveHierarchyState(android.util.SparseArray)
12246     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12247     * @see #setSaveEnabled(boolean)
12248     */
12249    protected Parcelable onSaveInstanceState() {
12250        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12251        return BaseSavedState.EMPTY_STATE;
12252    }
12253
12254    /**
12255     * Restore this view hierarchy's frozen state from the given container.
12256     *
12257     * @param container The SparseArray which holds previously frozen states.
12258     *
12259     * @see #saveHierarchyState(android.util.SparseArray)
12260     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12261     * @see #onRestoreInstanceState(android.os.Parcelable)
12262     */
12263    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12264        dispatchRestoreInstanceState(container);
12265    }
12266
12267    /**
12268     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12269     * state for this view and its children. May be overridden to modify how restoring
12270     * happens to a view's children; for example, some views may want to not store state
12271     * for their children.
12272     *
12273     * @param container The SparseArray which holds previously saved state.
12274     *
12275     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12276     * @see #restoreHierarchyState(android.util.SparseArray)
12277     * @see #onRestoreInstanceState(android.os.Parcelable)
12278     */
12279    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12280        if (mID != NO_ID) {
12281            Parcelable state = container.get(mID);
12282            if (state != null) {
12283                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12284                // + ": " + state);
12285                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12286                onRestoreInstanceState(state);
12287                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12288                    throw new IllegalStateException(
12289                            "Derived class did not call super.onRestoreInstanceState()");
12290                }
12291            }
12292        }
12293    }
12294
12295    /**
12296     * Hook allowing a view to re-apply a representation of its internal state that had previously
12297     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12298     * null state.
12299     *
12300     * @param state The frozen state that had previously been returned by
12301     *        {@link #onSaveInstanceState}.
12302     *
12303     * @see #onSaveInstanceState()
12304     * @see #restoreHierarchyState(android.util.SparseArray)
12305     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12306     */
12307    protected void onRestoreInstanceState(Parcelable state) {
12308        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12309        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12310            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12311                    + "received " + state.getClass().toString() + " instead. This usually happens "
12312                    + "when two views of different type have the same id in the same hierarchy. "
12313                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12314                    + "other views do not use the same id.");
12315        }
12316    }
12317
12318    /**
12319     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12320     *
12321     * @return the drawing start time in milliseconds
12322     */
12323    public long getDrawingTime() {
12324        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12325    }
12326
12327    /**
12328     * <p>Enables or disables the duplication of the parent's state into this view. When
12329     * duplication is enabled, this view gets its drawable state from its parent rather
12330     * than from its own internal properties.</p>
12331     *
12332     * <p>Note: in the current implementation, setting this property to true after the
12333     * view was added to a ViewGroup might have no effect at all. This property should
12334     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12335     *
12336     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12337     * property is enabled, an exception will be thrown.</p>
12338     *
12339     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12340     * parent, these states should not be affected by this method.</p>
12341     *
12342     * @param enabled True to enable duplication of the parent's drawable state, false
12343     *                to disable it.
12344     *
12345     * @see #getDrawableState()
12346     * @see #isDuplicateParentStateEnabled()
12347     */
12348    public void setDuplicateParentStateEnabled(boolean enabled) {
12349        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12350    }
12351
12352    /**
12353     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12354     *
12355     * @return True if this view's drawable state is duplicated from the parent,
12356     *         false otherwise
12357     *
12358     * @see #getDrawableState()
12359     * @see #setDuplicateParentStateEnabled(boolean)
12360     */
12361    public boolean isDuplicateParentStateEnabled() {
12362        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12363    }
12364
12365    /**
12366     * <p>Specifies the type of layer backing this view. The layer can be
12367     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12368     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12369     *
12370     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12371     * instance that controls how the layer is composed on screen. The following
12372     * properties of the paint are taken into account when composing the layer:</p>
12373     * <ul>
12374     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12375     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12376     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12377     * </ul>
12378     *
12379     * <p>If this view has an alpha value set to < 1.0 by calling
12380     * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded
12381     * by this view's alpha value.</p>
12382     *
12383     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE},
12384     * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE}
12385     * for more information on when and how to use layers.</p>
12386     *
12387     * @param layerType The type of layer to use with this view, must be one of
12388     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12389     *        {@link #LAYER_TYPE_HARDWARE}
12390     * @param paint The paint used to compose the layer. This argument is optional
12391     *        and can be null. It is ignored when the layer type is
12392     *        {@link #LAYER_TYPE_NONE}
12393     *
12394     * @see #getLayerType()
12395     * @see #LAYER_TYPE_NONE
12396     * @see #LAYER_TYPE_SOFTWARE
12397     * @see #LAYER_TYPE_HARDWARE
12398     * @see #setAlpha(float)
12399     *
12400     * @attr ref android.R.styleable#View_layerType
12401     */
12402    public void setLayerType(int layerType, Paint paint) {
12403        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12404            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12405                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12406        }
12407
12408        if (layerType == mLayerType) {
12409            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12410                mLayerPaint = paint == null ? new Paint() : paint;
12411                invalidateParentCaches();
12412                invalidate(true);
12413            }
12414            return;
12415        }
12416
12417        // Destroy any previous software drawing cache if needed
12418        switch (mLayerType) {
12419            case LAYER_TYPE_HARDWARE:
12420                destroyLayer(false);
12421                // fall through - non-accelerated views may use software layer mechanism instead
12422            case LAYER_TYPE_SOFTWARE:
12423                destroyDrawingCache();
12424                break;
12425            default:
12426                break;
12427        }
12428
12429        mLayerType = layerType;
12430        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12431        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12432        mLocalDirtyRect = layerDisabled ? null : new Rect();
12433
12434        invalidateParentCaches();
12435        invalidate(true);
12436    }
12437
12438    /**
12439     * Updates the {@link Paint} object used with the current layer (used only if the current
12440     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12441     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12442     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12443     * ensure that the view gets redrawn immediately.
12444     *
12445     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12446     * instance that controls how the layer is composed on screen. The following
12447     * properties of the paint are taken into account when composing the layer:</p>
12448     * <ul>
12449     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12450     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12451     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12452     * </ul>
12453     *
12454     * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the
12455     * alpha value of the layer's paint is superceded by this view's alpha value.</p>
12456     *
12457     * @param paint The paint used to compose the layer. This argument is optional
12458     *        and can be null. It is ignored when the layer type is
12459     *        {@link #LAYER_TYPE_NONE}
12460     *
12461     * @see #setLayerType(int, android.graphics.Paint)
12462     */
12463    public void setLayerPaint(Paint paint) {
12464        int layerType = getLayerType();
12465        if (layerType != LAYER_TYPE_NONE) {
12466            mLayerPaint = paint == null ? new Paint() : paint;
12467            if (layerType == LAYER_TYPE_HARDWARE) {
12468                HardwareLayer layer = getHardwareLayer();
12469                if (layer != null) {
12470                    layer.setLayerPaint(paint);
12471                }
12472                invalidateViewProperty(false, false);
12473            } else {
12474                invalidate();
12475            }
12476        }
12477    }
12478
12479    /**
12480     * Indicates whether this view has a static layer. A view with layer type
12481     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12482     * dynamic.
12483     */
12484    boolean hasStaticLayer() {
12485        return true;
12486    }
12487
12488    /**
12489     * Indicates what type of layer is currently associated with this view. By default
12490     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12491     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12492     * for more information on the different types of layers.
12493     *
12494     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12495     *         {@link #LAYER_TYPE_HARDWARE}
12496     *
12497     * @see #setLayerType(int, android.graphics.Paint)
12498     * @see #buildLayer()
12499     * @see #LAYER_TYPE_NONE
12500     * @see #LAYER_TYPE_SOFTWARE
12501     * @see #LAYER_TYPE_HARDWARE
12502     */
12503    public int getLayerType() {
12504        return mLayerType;
12505    }
12506
12507    /**
12508     * Forces this view's layer to be created and this view to be rendered
12509     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12510     * invoking this method will have no effect.
12511     *
12512     * This method can for instance be used to render a view into its layer before
12513     * starting an animation. If this view is complex, rendering into the layer
12514     * before starting the animation will avoid skipping frames.
12515     *
12516     * @throws IllegalStateException If this view is not attached to a window
12517     *
12518     * @see #setLayerType(int, android.graphics.Paint)
12519     */
12520    public void buildLayer() {
12521        if (mLayerType == LAYER_TYPE_NONE) return;
12522
12523        if (mAttachInfo == null) {
12524            throw new IllegalStateException("This view must be attached to a window first");
12525        }
12526
12527        switch (mLayerType) {
12528            case LAYER_TYPE_HARDWARE:
12529                if (mAttachInfo.mHardwareRenderer != null &&
12530                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12531                        mAttachInfo.mHardwareRenderer.validate()) {
12532                    getHardwareLayer();
12533                }
12534                break;
12535            case LAYER_TYPE_SOFTWARE:
12536                buildDrawingCache(true);
12537                break;
12538        }
12539    }
12540
12541    /**
12542     * <p>Returns a hardware layer that can be used to draw this view again
12543     * without executing its draw method.</p>
12544     *
12545     * @return A HardwareLayer ready to render, or null if an error occurred.
12546     */
12547    HardwareLayer getHardwareLayer() {
12548        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12549                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12550            return null;
12551        }
12552
12553        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12554
12555        final int width = mRight - mLeft;
12556        final int height = mBottom - mTop;
12557
12558        if (width == 0 || height == 0) {
12559            return null;
12560        }
12561
12562        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12563            if (mHardwareLayer == null) {
12564                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12565                        width, height, isOpaque());
12566                mLocalDirtyRect.set(0, 0, width, height);
12567            } else {
12568                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12569                    if (mHardwareLayer.resize(width, height)) {
12570                        mLocalDirtyRect.set(0, 0, width, height);
12571                    }
12572                }
12573
12574                // This should not be necessary but applications that change
12575                // the parameters of their background drawable without calling
12576                // this.setBackground(Drawable) can leave the view in a bad state
12577                // (for instance isOpaque() returns true, but the background is
12578                // not opaque.)
12579                computeOpaqueFlags();
12580
12581                final boolean opaque = isOpaque();
12582                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12583                    mHardwareLayer.setOpaque(opaque);
12584                    mLocalDirtyRect.set(0, 0, width, height);
12585                }
12586            }
12587
12588            // The layer is not valid if the underlying GPU resources cannot be allocated
12589            if (!mHardwareLayer.isValid()) {
12590                return null;
12591            }
12592
12593            mHardwareLayer.setLayerPaint(mLayerPaint);
12594            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12595            ViewRootImpl viewRoot = getViewRootImpl();
12596            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12597
12598            mLocalDirtyRect.setEmpty();
12599        }
12600
12601        return mHardwareLayer;
12602    }
12603
12604    /**
12605     * Destroys this View's hardware layer if possible.
12606     *
12607     * @return True if the layer was destroyed, false otherwise.
12608     *
12609     * @see #setLayerType(int, android.graphics.Paint)
12610     * @see #LAYER_TYPE_HARDWARE
12611     */
12612    boolean destroyLayer(boolean valid) {
12613        if (mHardwareLayer != null) {
12614            AttachInfo info = mAttachInfo;
12615            if (info != null && info.mHardwareRenderer != null &&
12616                    info.mHardwareRenderer.isEnabled() &&
12617                    (valid || info.mHardwareRenderer.validate())) {
12618                mHardwareLayer.destroy();
12619                mHardwareLayer = null;
12620
12621                if (mDisplayList != null) {
12622                    mDisplayList.reset();
12623                }
12624                invalidate(true);
12625                invalidateParentCaches();
12626            }
12627            return true;
12628        }
12629        return false;
12630    }
12631
12632    /**
12633     * Destroys all hardware rendering resources. This method is invoked
12634     * when the system needs to reclaim resources. Upon execution of this
12635     * method, you should free any OpenGL resources created by the view.
12636     *
12637     * Note: you <strong>must</strong> call
12638     * <code>super.destroyHardwareResources()</code> when overriding
12639     * this method.
12640     *
12641     * @hide
12642     */
12643    protected void destroyHardwareResources() {
12644        destroyLayer(true);
12645    }
12646
12647    /**
12648     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12649     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12650     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12651     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12652     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12653     * null.</p>
12654     *
12655     * <p>Enabling the drawing cache is similar to
12656     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12657     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12658     * drawing cache has no effect on rendering because the system uses a different mechanism
12659     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12660     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12661     * for information on how to enable software and hardware layers.</p>
12662     *
12663     * <p>This API can be used to manually generate
12664     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12665     * {@link #getDrawingCache()}.</p>
12666     *
12667     * @param enabled true to enable the drawing cache, false otherwise
12668     *
12669     * @see #isDrawingCacheEnabled()
12670     * @see #getDrawingCache()
12671     * @see #buildDrawingCache()
12672     * @see #setLayerType(int, android.graphics.Paint)
12673     */
12674    public void setDrawingCacheEnabled(boolean enabled) {
12675        mCachingFailed = false;
12676        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12677    }
12678
12679    /**
12680     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12681     *
12682     * @return true if the drawing cache is enabled
12683     *
12684     * @see #setDrawingCacheEnabled(boolean)
12685     * @see #getDrawingCache()
12686     */
12687    @ViewDebug.ExportedProperty(category = "drawing")
12688    public boolean isDrawingCacheEnabled() {
12689        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12690    }
12691
12692    /**
12693     * Debugging utility which recursively outputs the dirty state of a view and its
12694     * descendants.
12695     *
12696     * @hide
12697     */
12698    @SuppressWarnings({"UnusedDeclaration"})
12699    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12700        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12701                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12702                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12703                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12704        if (clear) {
12705            mPrivateFlags &= clearMask;
12706        }
12707        if (this instanceof ViewGroup) {
12708            ViewGroup parent = (ViewGroup) this;
12709            final int count = parent.getChildCount();
12710            for (int i = 0; i < count; i++) {
12711                final View child = parent.getChildAt(i);
12712                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12713            }
12714        }
12715    }
12716
12717    /**
12718     * This method is used by ViewGroup to cause its children to restore or recreate their
12719     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12720     * to recreate its own display list, which would happen if it went through the normal
12721     * draw/dispatchDraw mechanisms.
12722     *
12723     * @hide
12724     */
12725    protected void dispatchGetDisplayList() {}
12726
12727    /**
12728     * A view that is not attached or hardware accelerated cannot create a display list.
12729     * This method checks these conditions and returns the appropriate result.
12730     *
12731     * @return true if view has the ability to create a display list, false otherwise.
12732     *
12733     * @hide
12734     */
12735    public boolean canHaveDisplayList() {
12736        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12737    }
12738
12739    /**
12740     * @return The {@link HardwareRenderer} associated with that view or null if
12741     *         hardware rendering is not supported or this view is not attached
12742     *         to a window.
12743     *
12744     * @hide
12745     */
12746    public HardwareRenderer getHardwareRenderer() {
12747        if (mAttachInfo != null) {
12748            return mAttachInfo.mHardwareRenderer;
12749        }
12750        return null;
12751    }
12752
12753    /**
12754     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12755     * Otherwise, the same display list will be returned (after having been rendered into
12756     * along the way, depending on the invalidation state of the view).
12757     *
12758     * @param displayList The previous version of this displayList, could be null.
12759     * @param isLayer Whether the requester of the display list is a layer. If so,
12760     * the view will avoid creating a layer inside the resulting display list.
12761     * @return A new or reused DisplayList object.
12762     */
12763    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12764        if (!canHaveDisplayList()) {
12765            return null;
12766        }
12767
12768        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12769                displayList == null || !displayList.isValid() ||
12770                (!isLayer && mRecreateDisplayList))) {
12771            // Don't need to recreate the display list, just need to tell our
12772            // children to restore/recreate theirs
12773            if (displayList != null && displayList.isValid() &&
12774                    !isLayer && !mRecreateDisplayList) {
12775                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12776                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12777                dispatchGetDisplayList();
12778
12779                return displayList;
12780            }
12781
12782            if (!isLayer) {
12783                // If we got here, we're recreating it. Mark it as such to ensure that
12784                // we copy in child display lists into ours in drawChild()
12785                mRecreateDisplayList = true;
12786            }
12787            if (displayList == null) {
12788                final String name = getClass().getSimpleName();
12789                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12790                // If we're creating a new display list, make sure our parent gets invalidated
12791                // since they will need to recreate their display list to account for this
12792                // new child display list.
12793                invalidateParentCaches();
12794            }
12795
12796            boolean caching = false;
12797            int width = mRight - mLeft;
12798            int height = mBottom - mTop;
12799            int layerType = getLayerType();
12800
12801            final HardwareCanvas canvas = displayList.start(width, height);
12802
12803            try {
12804                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12805                    if (layerType == LAYER_TYPE_HARDWARE) {
12806                        final HardwareLayer layer = getHardwareLayer();
12807                        if (layer != null && layer.isValid()) {
12808                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12809                        } else {
12810                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12811                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12812                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12813                        }
12814                        caching = true;
12815                    } else {
12816                        buildDrawingCache(true);
12817                        Bitmap cache = getDrawingCache(true);
12818                        if (cache != null) {
12819                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12820                            caching = true;
12821                        }
12822                    }
12823                } else {
12824
12825                    computeScroll();
12826
12827                    canvas.translate(-mScrollX, -mScrollY);
12828                    if (!isLayer) {
12829                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12830                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12831                    }
12832
12833                    // Fast path for layouts with no backgrounds
12834                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12835                        dispatchDraw(canvas);
12836                        if (mOverlay != null && !mOverlay.isEmpty()) {
12837                            mOverlay.getOverlayView().draw(canvas);
12838                        }
12839                    } else {
12840                        draw(canvas);
12841                    }
12842                }
12843            } finally {
12844                displayList.end();
12845                displayList.setCaching(caching);
12846                if (isLayer) {
12847                    displayList.setLeftTopRightBottom(0, 0, width, height);
12848                } else {
12849                    setDisplayListProperties(displayList);
12850                }
12851            }
12852        } else if (!isLayer) {
12853            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12854            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12855        }
12856
12857        return displayList;
12858    }
12859
12860    /**
12861     * Get the DisplayList for the HardwareLayer
12862     *
12863     * @param layer The HardwareLayer whose DisplayList we want
12864     * @return A DisplayList fopr the specified HardwareLayer
12865     */
12866    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12867        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12868        layer.setDisplayList(displayList);
12869        return displayList;
12870    }
12871
12872
12873    /**
12874     * <p>Returns a display list that can be used to draw this view again
12875     * without executing its draw method.</p>
12876     *
12877     * @return A DisplayList ready to replay, or null if caching is not enabled.
12878     *
12879     * @hide
12880     */
12881    public DisplayList getDisplayList() {
12882        mDisplayList = getDisplayList(mDisplayList, false);
12883        return mDisplayList;
12884    }
12885
12886    private void clearDisplayList() {
12887        if (mDisplayList != null) {
12888            mDisplayList.clear();
12889        }
12890    }
12891
12892    /**
12893     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12894     *
12895     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12896     *
12897     * @see #getDrawingCache(boolean)
12898     */
12899    public Bitmap getDrawingCache() {
12900        return getDrawingCache(false);
12901    }
12902
12903    /**
12904     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12905     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12906     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12907     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12908     * request the drawing cache by calling this method and draw it on screen if the
12909     * returned bitmap is not null.</p>
12910     *
12911     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12912     * this method will create a bitmap of the same size as this view. Because this bitmap
12913     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12914     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12915     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12916     * size than the view. This implies that your application must be able to handle this
12917     * size.</p>
12918     *
12919     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12920     *        the current density of the screen when the application is in compatibility
12921     *        mode.
12922     *
12923     * @return A bitmap representing this view or null if cache is disabled.
12924     *
12925     * @see #setDrawingCacheEnabled(boolean)
12926     * @see #isDrawingCacheEnabled()
12927     * @see #buildDrawingCache(boolean)
12928     * @see #destroyDrawingCache()
12929     */
12930    public Bitmap getDrawingCache(boolean autoScale) {
12931        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12932            return null;
12933        }
12934        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12935            buildDrawingCache(autoScale);
12936        }
12937        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12938    }
12939
12940    /**
12941     * <p>Frees the resources used by the drawing cache. If you call
12942     * {@link #buildDrawingCache()} manually without calling
12943     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12944     * should cleanup the cache with this method afterwards.</p>
12945     *
12946     * @see #setDrawingCacheEnabled(boolean)
12947     * @see #buildDrawingCache()
12948     * @see #getDrawingCache()
12949     */
12950    public void destroyDrawingCache() {
12951        if (mDrawingCache != null) {
12952            mDrawingCache.recycle();
12953            mDrawingCache = null;
12954        }
12955        if (mUnscaledDrawingCache != null) {
12956            mUnscaledDrawingCache.recycle();
12957            mUnscaledDrawingCache = null;
12958        }
12959    }
12960
12961    /**
12962     * Setting a solid background color for the drawing cache's bitmaps will improve
12963     * performance and memory usage. Note, though that this should only be used if this
12964     * view will always be drawn on top of a solid color.
12965     *
12966     * @param color The background color to use for the drawing cache's bitmap
12967     *
12968     * @see #setDrawingCacheEnabled(boolean)
12969     * @see #buildDrawingCache()
12970     * @see #getDrawingCache()
12971     */
12972    public void setDrawingCacheBackgroundColor(int color) {
12973        if (color != mDrawingCacheBackgroundColor) {
12974            mDrawingCacheBackgroundColor = color;
12975            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12976        }
12977    }
12978
12979    /**
12980     * @see #setDrawingCacheBackgroundColor(int)
12981     *
12982     * @return The background color to used for the drawing cache's bitmap
12983     */
12984    public int getDrawingCacheBackgroundColor() {
12985        return mDrawingCacheBackgroundColor;
12986    }
12987
12988    /**
12989     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12990     *
12991     * @see #buildDrawingCache(boolean)
12992     */
12993    public void buildDrawingCache() {
12994        buildDrawingCache(false);
12995    }
12996
12997    /**
12998     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12999     *
13000     * <p>If you call {@link #buildDrawingCache()} manually without calling
13001     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
13002     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
13003     *
13004     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
13005     * this method will create a bitmap of the same size as this view. Because this bitmap
13006     * will be drawn scaled by the parent ViewGroup, the result on screen might show
13007     * scaling artifacts. To avoid such artifacts, you should call this method by setting
13008     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
13009     * size than the view. This implies that your application must be able to handle this
13010     * size.</p>
13011     *
13012     * <p>You should avoid calling this method when hardware acceleration is enabled. If
13013     * you do not need the drawing cache bitmap, calling this method will increase memory
13014     * usage and cause the view to be rendered in software once, thus negatively impacting
13015     * performance.</p>
13016     *
13017     * @see #getDrawingCache()
13018     * @see #destroyDrawingCache()
13019     */
13020    public void buildDrawingCache(boolean autoScale) {
13021        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
13022                mDrawingCache == null : mUnscaledDrawingCache == null)) {
13023            mCachingFailed = false;
13024
13025            int width = mRight - mLeft;
13026            int height = mBottom - mTop;
13027
13028            final AttachInfo attachInfo = mAttachInfo;
13029            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13030
13031            if (autoScale && scalingRequired) {
13032                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13033                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13034            }
13035
13036            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13037            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13038            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13039
13040            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13041            final long drawingCacheSize =
13042                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13043            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13044                if (width > 0 && height > 0) {
13045                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13046                            + projectedBitmapSize + " bytes, only "
13047                            + drawingCacheSize + " available");
13048                }
13049                destroyDrawingCache();
13050                mCachingFailed = true;
13051                return;
13052            }
13053
13054            boolean clear = true;
13055            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13056
13057            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13058                Bitmap.Config quality;
13059                if (!opaque) {
13060                    // Never pick ARGB_4444 because it looks awful
13061                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13062                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13063                        case DRAWING_CACHE_QUALITY_AUTO:
13064                            quality = Bitmap.Config.ARGB_8888;
13065                            break;
13066                        case DRAWING_CACHE_QUALITY_LOW:
13067                            quality = Bitmap.Config.ARGB_8888;
13068                            break;
13069                        case DRAWING_CACHE_QUALITY_HIGH:
13070                            quality = Bitmap.Config.ARGB_8888;
13071                            break;
13072                        default:
13073                            quality = Bitmap.Config.ARGB_8888;
13074                            break;
13075                    }
13076                } else {
13077                    // Optimization for translucent windows
13078                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13079                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13080                }
13081
13082                // Try to cleanup memory
13083                if (bitmap != null) bitmap.recycle();
13084
13085                try {
13086                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13087                            width, height, quality);
13088                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13089                    if (autoScale) {
13090                        mDrawingCache = bitmap;
13091                    } else {
13092                        mUnscaledDrawingCache = bitmap;
13093                    }
13094                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13095                } catch (OutOfMemoryError e) {
13096                    // If there is not enough memory to create the bitmap cache, just
13097                    // ignore the issue as bitmap caches are not required to draw the
13098                    // view hierarchy
13099                    if (autoScale) {
13100                        mDrawingCache = null;
13101                    } else {
13102                        mUnscaledDrawingCache = null;
13103                    }
13104                    mCachingFailed = true;
13105                    return;
13106                }
13107
13108                clear = drawingCacheBackgroundColor != 0;
13109            }
13110
13111            Canvas canvas;
13112            if (attachInfo != null) {
13113                canvas = attachInfo.mCanvas;
13114                if (canvas == null) {
13115                    canvas = new Canvas();
13116                }
13117                canvas.setBitmap(bitmap);
13118                // Temporarily clobber the cached Canvas in case one of our children
13119                // is also using a drawing cache. Without this, the children would
13120                // steal the canvas by attaching their own bitmap to it and bad, bad
13121                // thing would happen (invisible views, corrupted drawings, etc.)
13122                attachInfo.mCanvas = null;
13123            } else {
13124                // This case should hopefully never or seldom happen
13125                canvas = new Canvas(bitmap);
13126            }
13127
13128            if (clear) {
13129                bitmap.eraseColor(drawingCacheBackgroundColor);
13130            }
13131
13132            computeScroll();
13133            final int restoreCount = canvas.save();
13134
13135            if (autoScale && scalingRequired) {
13136                final float scale = attachInfo.mApplicationScale;
13137                canvas.scale(scale, scale);
13138            }
13139
13140            canvas.translate(-mScrollX, -mScrollY);
13141
13142            mPrivateFlags |= PFLAG_DRAWN;
13143            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13144                    mLayerType != LAYER_TYPE_NONE) {
13145                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13146            }
13147
13148            // Fast path for layouts with no backgrounds
13149            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13150                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13151                dispatchDraw(canvas);
13152                if (mOverlay != null && !mOverlay.isEmpty()) {
13153                    mOverlay.getOverlayView().draw(canvas);
13154                }
13155            } else {
13156                draw(canvas);
13157            }
13158
13159            canvas.restoreToCount(restoreCount);
13160            canvas.setBitmap(null);
13161
13162            if (attachInfo != null) {
13163                // Restore the cached Canvas for our siblings
13164                attachInfo.mCanvas = canvas;
13165            }
13166        }
13167    }
13168
13169    /**
13170     * Create a snapshot of the view into a bitmap.  We should probably make
13171     * some form of this public, but should think about the API.
13172     */
13173    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13174        int width = mRight - mLeft;
13175        int height = mBottom - mTop;
13176
13177        final AttachInfo attachInfo = mAttachInfo;
13178        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13179        width = (int) ((width * scale) + 0.5f);
13180        height = (int) ((height * scale) + 0.5f);
13181
13182        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13183                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13184        if (bitmap == null) {
13185            throw new OutOfMemoryError();
13186        }
13187
13188        Resources resources = getResources();
13189        if (resources != null) {
13190            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13191        }
13192
13193        Canvas canvas;
13194        if (attachInfo != null) {
13195            canvas = attachInfo.mCanvas;
13196            if (canvas == null) {
13197                canvas = new Canvas();
13198            }
13199            canvas.setBitmap(bitmap);
13200            // Temporarily clobber the cached Canvas in case one of our children
13201            // is also using a drawing cache. Without this, the children would
13202            // steal the canvas by attaching their own bitmap to it and bad, bad
13203            // things would happen (invisible views, corrupted drawings, etc.)
13204            attachInfo.mCanvas = null;
13205        } else {
13206            // This case should hopefully never or seldom happen
13207            canvas = new Canvas(bitmap);
13208        }
13209
13210        if ((backgroundColor & 0xff000000) != 0) {
13211            bitmap.eraseColor(backgroundColor);
13212        }
13213
13214        computeScroll();
13215        final int restoreCount = canvas.save();
13216        canvas.scale(scale, scale);
13217        canvas.translate(-mScrollX, -mScrollY);
13218
13219        // Temporarily remove the dirty mask
13220        int flags = mPrivateFlags;
13221        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13222
13223        // Fast path for layouts with no backgrounds
13224        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13225            dispatchDraw(canvas);
13226        } else {
13227            draw(canvas);
13228        }
13229
13230        mPrivateFlags = flags;
13231
13232        canvas.restoreToCount(restoreCount);
13233        canvas.setBitmap(null);
13234
13235        if (attachInfo != null) {
13236            // Restore the cached Canvas for our siblings
13237            attachInfo.mCanvas = canvas;
13238        }
13239
13240        return bitmap;
13241    }
13242
13243    /**
13244     * Indicates whether this View is currently in edit mode. A View is usually
13245     * in edit mode when displayed within a developer tool. For instance, if
13246     * this View is being drawn by a visual user interface builder, this method
13247     * should return true.
13248     *
13249     * Subclasses should check the return value of this method to provide
13250     * different behaviors if their normal behavior might interfere with the
13251     * host environment. For instance: the class spawns a thread in its
13252     * constructor, the drawing code relies on device-specific features, etc.
13253     *
13254     * This method is usually checked in the drawing code of custom widgets.
13255     *
13256     * @return True if this View is in edit mode, false otherwise.
13257     */
13258    public boolean isInEditMode() {
13259        return false;
13260    }
13261
13262    /**
13263     * If the View draws content inside its padding and enables fading edges,
13264     * it needs to support padding offsets. Padding offsets are added to the
13265     * fading edges to extend the length of the fade so that it covers pixels
13266     * drawn inside the padding.
13267     *
13268     * Subclasses of this class should override this method if they need
13269     * to draw content inside the padding.
13270     *
13271     * @return True if padding offset must be applied, false otherwise.
13272     *
13273     * @see #getLeftPaddingOffset()
13274     * @see #getRightPaddingOffset()
13275     * @see #getTopPaddingOffset()
13276     * @see #getBottomPaddingOffset()
13277     *
13278     * @since CURRENT
13279     */
13280    protected boolean isPaddingOffsetRequired() {
13281        return false;
13282    }
13283
13284    /**
13285     * Amount by which to extend the left fading region. Called only when
13286     * {@link #isPaddingOffsetRequired()} returns true.
13287     *
13288     * @return The left padding offset in pixels.
13289     *
13290     * @see #isPaddingOffsetRequired()
13291     *
13292     * @since CURRENT
13293     */
13294    protected int getLeftPaddingOffset() {
13295        return 0;
13296    }
13297
13298    /**
13299     * Amount by which to extend the right fading region. Called only when
13300     * {@link #isPaddingOffsetRequired()} returns true.
13301     *
13302     * @return The right padding offset in pixels.
13303     *
13304     * @see #isPaddingOffsetRequired()
13305     *
13306     * @since CURRENT
13307     */
13308    protected int getRightPaddingOffset() {
13309        return 0;
13310    }
13311
13312    /**
13313     * Amount by which to extend the top fading region. Called only when
13314     * {@link #isPaddingOffsetRequired()} returns true.
13315     *
13316     * @return The top padding offset in pixels.
13317     *
13318     * @see #isPaddingOffsetRequired()
13319     *
13320     * @since CURRENT
13321     */
13322    protected int getTopPaddingOffset() {
13323        return 0;
13324    }
13325
13326    /**
13327     * Amount by which to extend the bottom fading region. Called only when
13328     * {@link #isPaddingOffsetRequired()} returns true.
13329     *
13330     * @return The bottom padding offset in pixels.
13331     *
13332     * @see #isPaddingOffsetRequired()
13333     *
13334     * @since CURRENT
13335     */
13336    protected int getBottomPaddingOffset() {
13337        return 0;
13338    }
13339
13340    /**
13341     * @hide
13342     * @param offsetRequired
13343     */
13344    protected int getFadeTop(boolean offsetRequired) {
13345        int top = mPaddingTop;
13346        if (offsetRequired) top += getTopPaddingOffset();
13347        return top;
13348    }
13349
13350    /**
13351     * @hide
13352     * @param offsetRequired
13353     */
13354    protected int getFadeHeight(boolean offsetRequired) {
13355        int padding = mPaddingTop;
13356        if (offsetRequired) padding += getTopPaddingOffset();
13357        return mBottom - mTop - mPaddingBottom - padding;
13358    }
13359
13360    /**
13361     * <p>Indicates whether this view is attached to a hardware accelerated
13362     * window or not.</p>
13363     *
13364     * <p>Even if this method returns true, it does not mean that every call
13365     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13366     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13367     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13368     * window is hardware accelerated,
13369     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13370     * return false, and this method will return true.</p>
13371     *
13372     * @return True if the view is attached to a window and the window is
13373     *         hardware accelerated; false in any other case.
13374     */
13375    public boolean isHardwareAccelerated() {
13376        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13377    }
13378
13379    /**
13380     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13381     * case of an active Animation being run on the view.
13382     */
13383    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13384            Animation a, boolean scalingRequired) {
13385        Transformation invalidationTransform;
13386        final int flags = parent.mGroupFlags;
13387        final boolean initialized = a.isInitialized();
13388        if (!initialized) {
13389            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13390            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13391            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13392            onAnimationStart();
13393        }
13394
13395        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
13396        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13397            if (parent.mInvalidationTransformation == null) {
13398                parent.mInvalidationTransformation = new Transformation();
13399            }
13400            invalidationTransform = parent.mInvalidationTransformation;
13401            a.getTransformation(drawingTime, invalidationTransform, 1f);
13402        } else {
13403            invalidationTransform = parent.mChildTransformation;
13404        }
13405
13406        if (more) {
13407            if (!a.willChangeBounds()) {
13408                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13409                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13410                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13411                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13412                    // The child need to draw an animation, potentially offscreen, so
13413                    // make sure we do not cancel invalidate requests
13414                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13415                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13416                }
13417            } else {
13418                if (parent.mInvalidateRegion == null) {
13419                    parent.mInvalidateRegion = new RectF();
13420                }
13421                final RectF region = parent.mInvalidateRegion;
13422                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13423                        invalidationTransform);
13424
13425                // The child need to draw an animation, potentially offscreen, so
13426                // make sure we do not cancel invalidate requests
13427                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13428
13429                final int left = mLeft + (int) region.left;
13430                final int top = mTop + (int) region.top;
13431                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13432                        top + (int) (region.height() + .5f));
13433            }
13434        }
13435        return more;
13436    }
13437
13438    /**
13439     * This method is called by getDisplayList() when a display list is created or re-rendered.
13440     * It sets or resets the current value of all properties on that display list (resetting is
13441     * necessary when a display list is being re-created, because we need to make sure that
13442     * previously-set transform values
13443     */
13444    void setDisplayListProperties(DisplayList displayList) {
13445        if (displayList != null) {
13446            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13447            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13448            if (mParent instanceof ViewGroup) {
13449                displayList.setClipChildren(
13450                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13451            }
13452            float alpha = 1;
13453            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13454                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13455                ViewGroup parentVG = (ViewGroup) mParent;
13456                final boolean hasTransform =
13457                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13458                if (hasTransform) {
13459                    Transformation transform = parentVG.mChildTransformation;
13460                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13461                    if (transformType != Transformation.TYPE_IDENTITY) {
13462                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13463                            alpha = transform.getAlpha();
13464                        }
13465                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13466                            displayList.setMatrix(transform.getMatrix());
13467                        }
13468                    }
13469                }
13470            }
13471            if (mTransformationInfo != null) {
13472                alpha *= mTransformationInfo.mAlpha;
13473                if (alpha < 1) {
13474                    final int multipliedAlpha = (int) (255 * alpha);
13475                    if (onSetAlpha(multipliedAlpha)) {
13476                        alpha = 1;
13477                    }
13478                }
13479                displayList.setTransformationInfo(alpha,
13480                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13481                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13482                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13483                        mTransformationInfo.mScaleY);
13484                if (mTransformationInfo.mCamera == null) {
13485                    mTransformationInfo.mCamera = new Camera();
13486                    mTransformationInfo.matrix3D = new Matrix();
13487                }
13488                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13489                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13490                    displayList.setPivotX(getPivotX());
13491                    displayList.setPivotY(getPivotY());
13492                }
13493            } else if (alpha < 1) {
13494                displayList.setAlpha(alpha);
13495            }
13496        }
13497    }
13498
13499    /**
13500     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13501     * This draw() method is an implementation detail and is not intended to be overridden or
13502     * to be called from anywhere else other than ViewGroup.drawChild().
13503     */
13504    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13505        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13506        boolean more = false;
13507        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13508        final int flags = parent.mGroupFlags;
13509
13510        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13511            parent.mChildTransformation.clear();
13512            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13513        }
13514
13515        Transformation transformToApply = null;
13516        boolean concatMatrix = false;
13517
13518        boolean scalingRequired = false;
13519        boolean caching;
13520        int layerType = getLayerType();
13521
13522        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13523        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13524                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13525            caching = true;
13526            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13527            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13528        } else {
13529            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13530        }
13531
13532        final Animation a = getAnimation();
13533        if (a != null) {
13534            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13535            concatMatrix = a.willChangeTransformationMatrix();
13536            if (concatMatrix) {
13537                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13538            }
13539            transformToApply = parent.mChildTransformation;
13540        } else {
13541            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13542                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13543                // No longer animating: clear out old animation matrix
13544                mDisplayList.setAnimationMatrix(null);
13545                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13546            }
13547            if (!useDisplayListProperties &&
13548                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13549                final boolean hasTransform =
13550                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13551                if (hasTransform) {
13552                    final int transformType = parent.mChildTransformation.getTransformationType();
13553                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13554                            parent.mChildTransformation : null;
13555                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13556                }
13557            }
13558        }
13559
13560        concatMatrix |= !childHasIdentityMatrix;
13561
13562        // Sets the flag as early as possible to allow draw() implementations
13563        // to call invalidate() successfully when doing animations
13564        mPrivateFlags |= PFLAG_DRAWN;
13565
13566        if (!concatMatrix &&
13567                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13568                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13569                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13570                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13571            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13572            return more;
13573        }
13574        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13575
13576        if (hardwareAccelerated) {
13577            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13578            // retain the flag's value temporarily in the mRecreateDisplayList flag
13579            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13580            mPrivateFlags &= ~PFLAG_INVALIDATED;
13581        }
13582
13583        DisplayList displayList = null;
13584        Bitmap cache = null;
13585        boolean hasDisplayList = false;
13586        if (caching) {
13587            if (!hardwareAccelerated) {
13588                if (layerType != LAYER_TYPE_NONE) {
13589                    layerType = LAYER_TYPE_SOFTWARE;
13590                    buildDrawingCache(true);
13591                }
13592                cache = getDrawingCache(true);
13593            } else {
13594                switch (layerType) {
13595                    case LAYER_TYPE_SOFTWARE:
13596                        if (useDisplayListProperties) {
13597                            hasDisplayList = canHaveDisplayList();
13598                        } else {
13599                            buildDrawingCache(true);
13600                            cache = getDrawingCache(true);
13601                        }
13602                        break;
13603                    case LAYER_TYPE_HARDWARE:
13604                        if (useDisplayListProperties) {
13605                            hasDisplayList = canHaveDisplayList();
13606                        }
13607                        break;
13608                    case LAYER_TYPE_NONE:
13609                        // Delay getting the display list until animation-driven alpha values are
13610                        // set up and possibly passed on to the view
13611                        hasDisplayList = canHaveDisplayList();
13612                        break;
13613                }
13614            }
13615        }
13616        useDisplayListProperties &= hasDisplayList;
13617        if (useDisplayListProperties) {
13618            displayList = getDisplayList();
13619            if (!displayList.isValid()) {
13620                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13621                // to getDisplayList(), the display list will be marked invalid and we should not
13622                // try to use it again.
13623                displayList = null;
13624                hasDisplayList = false;
13625                useDisplayListProperties = false;
13626            }
13627        }
13628
13629        int sx = 0;
13630        int sy = 0;
13631        if (!hasDisplayList) {
13632            computeScroll();
13633            sx = mScrollX;
13634            sy = mScrollY;
13635        }
13636
13637        final boolean hasNoCache = cache == null || hasDisplayList;
13638        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13639                layerType != LAYER_TYPE_HARDWARE;
13640
13641        int restoreTo = -1;
13642        if (!useDisplayListProperties || transformToApply != null) {
13643            restoreTo = canvas.save();
13644        }
13645        if (offsetForScroll) {
13646            canvas.translate(mLeft - sx, mTop - sy);
13647        } else {
13648            if (!useDisplayListProperties) {
13649                canvas.translate(mLeft, mTop);
13650            }
13651            if (scalingRequired) {
13652                if (useDisplayListProperties) {
13653                    // TODO: Might not need this if we put everything inside the DL
13654                    restoreTo = canvas.save();
13655                }
13656                // mAttachInfo cannot be null, otherwise scalingRequired == false
13657                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13658                canvas.scale(scale, scale);
13659            }
13660        }
13661
13662        float alpha = useDisplayListProperties ? 1 : getAlpha();
13663        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13664                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13665            if (transformToApply != null || !childHasIdentityMatrix) {
13666                int transX = 0;
13667                int transY = 0;
13668
13669                if (offsetForScroll) {
13670                    transX = -sx;
13671                    transY = -sy;
13672                }
13673
13674                if (transformToApply != null) {
13675                    if (concatMatrix) {
13676                        if (useDisplayListProperties) {
13677                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13678                        } else {
13679                            // Undo the scroll translation, apply the transformation matrix,
13680                            // then redo the scroll translate to get the correct result.
13681                            canvas.translate(-transX, -transY);
13682                            canvas.concat(transformToApply.getMatrix());
13683                            canvas.translate(transX, transY);
13684                        }
13685                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13686                    }
13687
13688                    float transformAlpha = transformToApply.getAlpha();
13689                    if (transformAlpha < 1) {
13690                        alpha *= transformAlpha;
13691                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13692                    }
13693                }
13694
13695                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13696                    canvas.translate(-transX, -transY);
13697                    canvas.concat(getMatrix());
13698                    canvas.translate(transX, transY);
13699                }
13700            }
13701
13702            // Deal with alpha if it is or used to be <1
13703            if (alpha < 1 ||
13704                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13705                if (alpha < 1) {
13706                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13707                } else {
13708                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13709                }
13710                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13711                if (hasNoCache) {
13712                    final int multipliedAlpha = (int) (255 * alpha);
13713                    if (!onSetAlpha(multipliedAlpha)) {
13714                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13715                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13716                                layerType != LAYER_TYPE_NONE) {
13717                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13718                        }
13719                        if (useDisplayListProperties) {
13720                            displayList.setAlpha(alpha * getAlpha());
13721                        } else  if (layerType == LAYER_TYPE_NONE) {
13722                            final int scrollX = hasDisplayList ? 0 : sx;
13723                            final int scrollY = hasDisplayList ? 0 : sy;
13724                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13725                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13726                        }
13727                    } else {
13728                        // Alpha is handled by the child directly, clobber the layer's alpha
13729                        mPrivateFlags |= PFLAG_ALPHA_SET;
13730                    }
13731                }
13732            }
13733        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13734            onSetAlpha(255);
13735            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13736        }
13737
13738        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13739                !useDisplayListProperties && layerType == LAYER_TYPE_NONE) {
13740            if (offsetForScroll) {
13741                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13742            } else {
13743                if (!scalingRequired || cache == null) {
13744                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13745                } else {
13746                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13747                }
13748            }
13749        }
13750
13751        if (!useDisplayListProperties && hasDisplayList) {
13752            displayList = getDisplayList();
13753            if (!displayList.isValid()) {
13754                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13755                // to getDisplayList(), the display list will be marked invalid and we should not
13756                // try to use it again.
13757                displayList = null;
13758                hasDisplayList = false;
13759            }
13760        }
13761
13762        if (hasNoCache) {
13763            boolean layerRendered = false;
13764            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13765                final HardwareLayer layer = getHardwareLayer();
13766                if (layer != null && layer.isValid()) {
13767                    mLayerPaint.setAlpha((int) (alpha * 255));
13768                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13769                    layerRendered = true;
13770                } else {
13771                    final int scrollX = hasDisplayList ? 0 : sx;
13772                    final int scrollY = hasDisplayList ? 0 : sy;
13773                    canvas.saveLayer(scrollX, scrollY,
13774                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13775                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13776                }
13777            }
13778
13779            if (!layerRendered) {
13780                if (!hasDisplayList) {
13781                    // Fast path for layouts with no backgrounds
13782                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13783                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13784                        dispatchDraw(canvas);
13785                    } else {
13786                        draw(canvas);
13787                    }
13788                } else {
13789                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13790                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13791                }
13792            }
13793        } else if (cache != null) {
13794            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13795            Paint cachePaint;
13796
13797            if (layerType == LAYER_TYPE_NONE) {
13798                cachePaint = parent.mCachePaint;
13799                if (cachePaint == null) {
13800                    cachePaint = new Paint();
13801                    cachePaint.setDither(false);
13802                    parent.mCachePaint = cachePaint;
13803                }
13804                if (alpha < 1) {
13805                    cachePaint.setAlpha((int) (alpha * 255));
13806                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13807                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13808                    cachePaint.setAlpha(255);
13809                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13810                }
13811            } else {
13812                cachePaint = mLayerPaint;
13813                cachePaint.setAlpha((int) (alpha * 255));
13814            }
13815            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13816        }
13817
13818        if (restoreTo >= 0) {
13819            canvas.restoreToCount(restoreTo);
13820        }
13821
13822        if (a != null && !more) {
13823            if (!hardwareAccelerated && !a.getFillAfter()) {
13824                onSetAlpha(255);
13825            }
13826            parent.finishAnimatingView(this, a);
13827        }
13828
13829        if (more && hardwareAccelerated) {
13830            // invalidation is the trigger to recreate display lists, so if we're using
13831            // display lists to render, force an invalidate to allow the animation to
13832            // continue drawing another frame
13833            parent.invalidate(true);
13834            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13835                // alpha animations should cause the child to recreate its display list
13836                invalidate(true);
13837            }
13838        }
13839
13840        mRecreateDisplayList = false;
13841
13842        return more;
13843    }
13844
13845    /**
13846     * Manually render this view (and all of its children) to the given Canvas.
13847     * The view must have already done a full layout before this function is
13848     * called.  When implementing a view, implement
13849     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13850     * If you do need to override this method, call the superclass version.
13851     *
13852     * @param canvas The Canvas to which the View is rendered.
13853     */
13854    public void draw(Canvas canvas) {
13855        final int privateFlags = mPrivateFlags;
13856        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13857                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13858        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13859
13860        /*
13861         * Draw traversal performs several drawing steps which must be executed
13862         * in the appropriate order:
13863         *
13864         *      1. Draw the background
13865         *      2. If necessary, save the canvas' layers to prepare for fading
13866         *      3. Draw view's content
13867         *      4. Draw children
13868         *      5. If necessary, draw the fading edges and restore layers
13869         *      6. Draw decorations (scrollbars for instance)
13870         */
13871
13872        // Step 1, draw the background, if needed
13873        int saveCount;
13874
13875        if (!dirtyOpaque) {
13876            final Drawable background = mBackground;
13877            if (background != null) {
13878                final int scrollX = mScrollX;
13879                final int scrollY = mScrollY;
13880
13881                if (mBackgroundSizeChanged) {
13882                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13883                    mBackgroundSizeChanged = false;
13884                }
13885
13886                if ((scrollX | scrollY) == 0) {
13887                    background.draw(canvas);
13888                } else {
13889                    canvas.translate(scrollX, scrollY);
13890                    background.draw(canvas);
13891                    canvas.translate(-scrollX, -scrollY);
13892                }
13893            }
13894        }
13895
13896        // skip step 2 & 5 if possible (common case)
13897        final int viewFlags = mViewFlags;
13898        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13899        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13900        if (!verticalEdges && !horizontalEdges) {
13901            // Step 3, draw the content
13902            if (!dirtyOpaque) onDraw(canvas);
13903
13904            // Step 4, draw the children
13905            dispatchDraw(canvas);
13906
13907            // Step 6, draw decorations (scrollbars)
13908            onDrawScrollBars(canvas);
13909
13910            if (mOverlay != null && !mOverlay.isEmpty()) {
13911                mOverlay.getOverlayView().dispatchDraw(canvas);
13912            }
13913
13914            // we're done...
13915            return;
13916        }
13917
13918        /*
13919         * Here we do the full fledged routine...
13920         * (this is an uncommon case where speed matters less,
13921         * this is why we repeat some of the tests that have been
13922         * done above)
13923         */
13924
13925        boolean drawTop = false;
13926        boolean drawBottom = false;
13927        boolean drawLeft = false;
13928        boolean drawRight = false;
13929
13930        float topFadeStrength = 0.0f;
13931        float bottomFadeStrength = 0.0f;
13932        float leftFadeStrength = 0.0f;
13933        float rightFadeStrength = 0.0f;
13934
13935        // Step 2, save the canvas' layers
13936        int paddingLeft = mPaddingLeft;
13937
13938        final boolean offsetRequired = isPaddingOffsetRequired();
13939        if (offsetRequired) {
13940            paddingLeft += getLeftPaddingOffset();
13941        }
13942
13943        int left = mScrollX + paddingLeft;
13944        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13945        int top = mScrollY + getFadeTop(offsetRequired);
13946        int bottom = top + getFadeHeight(offsetRequired);
13947
13948        if (offsetRequired) {
13949            right += getRightPaddingOffset();
13950            bottom += getBottomPaddingOffset();
13951        }
13952
13953        final ScrollabilityCache scrollabilityCache = mScrollCache;
13954        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13955        int length = (int) fadeHeight;
13956
13957        // clip the fade length if top and bottom fades overlap
13958        // overlapping fades produce odd-looking artifacts
13959        if (verticalEdges && (top + length > bottom - length)) {
13960            length = (bottom - top) / 2;
13961        }
13962
13963        // also clip horizontal fades if necessary
13964        if (horizontalEdges && (left + length > right - length)) {
13965            length = (right - left) / 2;
13966        }
13967
13968        if (verticalEdges) {
13969            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13970            drawTop = topFadeStrength * fadeHeight > 1.0f;
13971            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13972            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13973        }
13974
13975        if (horizontalEdges) {
13976            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13977            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13978            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13979            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13980        }
13981
13982        saveCount = canvas.getSaveCount();
13983
13984        int solidColor = getSolidColor();
13985        if (solidColor == 0) {
13986            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13987
13988            if (drawTop) {
13989                canvas.saveLayer(left, top, right, top + length, null, flags);
13990            }
13991
13992            if (drawBottom) {
13993                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13994            }
13995
13996            if (drawLeft) {
13997                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13998            }
13999
14000            if (drawRight) {
14001                canvas.saveLayer(right - length, top, right, bottom, null, flags);
14002            }
14003        } else {
14004            scrollabilityCache.setFadeColor(solidColor);
14005        }
14006
14007        // Step 3, draw the content
14008        if (!dirtyOpaque) onDraw(canvas);
14009
14010        // Step 4, draw the children
14011        dispatchDraw(canvas);
14012
14013        // Step 5, draw the fade effect and restore layers
14014        final Paint p = scrollabilityCache.paint;
14015        final Matrix matrix = scrollabilityCache.matrix;
14016        final Shader fade = scrollabilityCache.shader;
14017
14018        if (drawTop) {
14019            matrix.setScale(1, fadeHeight * topFadeStrength);
14020            matrix.postTranslate(left, top);
14021            fade.setLocalMatrix(matrix);
14022            canvas.drawRect(left, top, right, top + length, p);
14023        }
14024
14025        if (drawBottom) {
14026            matrix.setScale(1, fadeHeight * bottomFadeStrength);
14027            matrix.postRotate(180);
14028            matrix.postTranslate(left, bottom);
14029            fade.setLocalMatrix(matrix);
14030            canvas.drawRect(left, bottom - length, right, bottom, p);
14031        }
14032
14033        if (drawLeft) {
14034            matrix.setScale(1, fadeHeight * leftFadeStrength);
14035            matrix.postRotate(-90);
14036            matrix.postTranslate(left, top);
14037            fade.setLocalMatrix(matrix);
14038            canvas.drawRect(left, top, left + length, bottom, p);
14039        }
14040
14041        if (drawRight) {
14042            matrix.setScale(1, fadeHeight * rightFadeStrength);
14043            matrix.postRotate(90);
14044            matrix.postTranslate(right, top);
14045            fade.setLocalMatrix(matrix);
14046            canvas.drawRect(right - length, top, right, bottom, p);
14047        }
14048
14049        canvas.restoreToCount(saveCount);
14050
14051        // Step 6, draw decorations (scrollbars)
14052        onDrawScrollBars(canvas);
14053
14054        if (mOverlay != null && !mOverlay.isEmpty()) {
14055            mOverlay.getOverlayView().dispatchDraw(canvas);
14056        }
14057    }
14058
14059    /**
14060     * Returns the overlay for this view, creating it if it does not yet exist.
14061     * Adding drawables to the overlay will cause them to be displayed whenever
14062     * the view itself is redrawn. Objects in the overlay should be actively
14063     * managed: remove them when they should not be displayed anymore. The
14064     * overlay will always have the same size as its host view.
14065     *
14066     * @return The ViewOverlay object for this view.
14067     * @see ViewOverlay
14068     */
14069    public ViewOverlay getOverlay() {
14070        if (mOverlay == null) {
14071            mOverlay = new ViewOverlay(mContext, this);
14072        }
14073        return mOverlay;
14074    }
14075
14076    /**
14077     * Override this if your view is known to always be drawn on top of a solid color background,
14078     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14079     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14080     * should be set to 0xFF.
14081     *
14082     * @see #setVerticalFadingEdgeEnabled(boolean)
14083     * @see #setHorizontalFadingEdgeEnabled(boolean)
14084     *
14085     * @return The known solid color background for this view, or 0 if the color may vary
14086     */
14087    @ViewDebug.ExportedProperty(category = "drawing")
14088    public int getSolidColor() {
14089        return 0;
14090    }
14091
14092    /**
14093     * Build a human readable string representation of the specified view flags.
14094     *
14095     * @param flags the view flags to convert to a string
14096     * @return a String representing the supplied flags
14097     */
14098    private static String printFlags(int flags) {
14099        String output = "";
14100        int numFlags = 0;
14101        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14102            output += "TAKES_FOCUS";
14103            numFlags++;
14104        }
14105
14106        switch (flags & VISIBILITY_MASK) {
14107        case INVISIBLE:
14108            if (numFlags > 0) {
14109                output += " ";
14110            }
14111            output += "INVISIBLE";
14112            // USELESS HERE numFlags++;
14113            break;
14114        case GONE:
14115            if (numFlags > 0) {
14116                output += " ";
14117            }
14118            output += "GONE";
14119            // USELESS HERE numFlags++;
14120            break;
14121        default:
14122            break;
14123        }
14124        return output;
14125    }
14126
14127    /**
14128     * Build a human readable string representation of the specified private
14129     * view flags.
14130     *
14131     * @param privateFlags the private view flags to convert to a string
14132     * @return a String representing the supplied flags
14133     */
14134    private static String printPrivateFlags(int privateFlags) {
14135        String output = "";
14136        int numFlags = 0;
14137
14138        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14139            output += "WANTS_FOCUS";
14140            numFlags++;
14141        }
14142
14143        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14144            if (numFlags > 0) {
14145                output += " ";
14146            }
14147            output += "FOCUSED";
14148            numFlags++;
14149        }
14150
14151        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14152            if (numFlags > 0) {
14153                output += " ";
14154            }
14155            output += "SELECTED";
14156            numFlags++;
14157        }
14158
14159        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14160            if (numFlags > 0) {
14161                output += " ";
14162            }
14163            output += "IS_ROOT_NAMESPACE";
14164            numFlags++;
14165        }
14166
14167        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14168            if (numFlags > 0) {
14169                output += " ";
14170            }
14171            output += "HAS_BOUNDS";
14172            numFlags++;
14173        }
14174
14175        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14176            if (numFlags > 0) {
14177                output += " ";
14178            }
14179            output += "DRAWN";
14180            // USELESS HERE numFlags++;
14181        }
14182        return output;
14183    }
14184
14185    /**
14186     * <p>Indicates whether or not this view's layout will be requested during
14187     * the next hierarchy layout pass.</p>
14188     *
14189     * @return true if the layout will be forced during next layout pass
14190     */
14191    public boolean isLayoutRequested() {
14192        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14193    }
14194
14195    /**
14196     * Return true if o is a ViewGroup that is laying out using optical bounds.
14197     * @hide
14198     */
14199    public static boolean isLayoutModeOptical(Object o) {
14200        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14201    }
14202
14203    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14204        Insets parentInsets = mParent instanceof View ?
14205                ((View) mParent).getOpticalInsets() : Insets.NONE;
14206        Insets childInsets = getOpticalInsets();
14207        return setFrame(
14208                left   + parentInsets.left - childInsets.left,
14209                top    + parentInsets.top  - childInsets.top,
14210                right  + parentInsets.left + childInsets.right,
14211                bottom + parentInsets.top  + childInsets.bottom);
14212    }
14213
14214    /**
14215     * Assign a size and position to a view and all of its
14216     * descendants
14217     *
14218     * <p>This is the second phase of the layout mechanism.
14219     * (The first is measuring). In this phase, each parent calls
14220     * layout on all of its children to position them.
14221     * This is typically done using the child measurements
14222     * that were stored in the measure pass().</p>
14223     *
14224     * <p>Derived classes should not override this method.
14225     * Derived classes with children should override
14226     * onLayout. In that method, they should
14227     * call layout on each of their children.</p>
14228     *
14229     * @param l Left position, relative to parent
14230     * @param t Top position, relative to parent
14231     * @param r Right position, relative to parent
14232     * @param b Bottom position, relative to parent
14233     */
14234    @SuppressWarnings({"unchecked"})
14235    public void layout(int l, int t, int r, int b) {
14236        int oldL = mLeft;
14237        int oldT = mTop;
14238        int oldB = mBottom;
14239        int oldR = mRight;
14240        boolean changed = isLayoutModeOptical(mParent) ?
14241                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14242        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14243            onLayout(changed, l, t, r, b);
14244            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14245
14246            ListenerInfo li = mListenerInfo;
14247            if (li != null && li.mOnLayoutChangeListeners != null) {
14248                ArrayList<OnLayoutChangeListener> listenersCopy =
14249                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14250                int numListeners = listenersCopy.size();
14251                for (int i = 0; i < numListeners; ++i) {
14252                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14253                }
14254            }
14255        }
14256        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14257    }
14258
14259    /**
14260     * Called from layout when this view should
14261     * assign a size and position to each of its children.
14262     *
14263     * Derived classes with children should override
14264     * this method and call layout on each of
14265     * their children.
14266     * @param changed This is a new size or position for this view
14267     * @param left Left position, relative to parent
14268     * @param top Top position, relative to parent
14269     * @param right Right position, relative to parent
14270     * @param bottom Bottom position, relative to parent
14271     */
14272    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14273    }
14274
14275    /**
14276     * Assign a size and position to this view.
14277     *
14278     * This is called from layout.
14279     *
14280     * @param left Left position, relative to parent
14281     * @param top Top position, relative to parent
14282     * @param right Right position, relative to parent
14283     * @param bottom Bottom position, relative to parent
14284     * @return true if the new size and position are different than the
14285     *         previous ones
14286     * {@hide}
14287     */
14288    protected boolean setFrame(int left, int top, int right, int bottom) {
14289        boolean changed = false;
14290
14291        if (DBG) {
14292            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14293                    + right + "," + bottom + ")");
14294        }
14295
14296        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14297            changed = true;
14298
14299            // Remember our drawn bit
14300            int drawn = mPrivateFlags & PFLAG_DRAWN;
14301
14302            int oldWidth = mRight - mLeft;
14303            int oldHeight = mBottom - mTop;
14304            int newWidth = right - left;
14305            int newHeight = bottom - top;
14306            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14307
14308            // Invalidate our old position
14309            invalidate(sizeChanged);
14310
14311            mLeft = left;
14312            mTop = top;
14313            mRight = right;
14314            mBottom = bottom;
14315            if (mDisplayList != null) {
14316                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14317            }
14318
14319            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14320
14321
14322            if (sizeChanged) {
14323                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14324                    // A change in dimension means an auto-centered pivot point changes, too
14325                    if (mTransformationInfo != null) {
14326                        mTransformationInfo.mMatrixDirty = true;
14327                    }
14328                }
14329                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
14330            }
14331
14332            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14333                // If we are visible, force the DRAWN bit to on so that
14334                // this invalidate will go through (at least to our parent).
14335                // This is because someone may have invalidated this view
14336                // before this call to setFrame came in, thereby clearing
14337                // the DRAWN bit.
14338                mPrivateFlags |= PFLAG_DRAWN;
14339                invalidate(sizeChanged);
14340                // parent display list may need to be recreated based on a change in the bounds
14341                // of any child
14342                invalidateParentCaches();
14343            }
14344
14345            // Reset drawn bit to original value (invalidate turns it off)
14346            mPrivateFlags |= drawn;
14347
14348            mBackgroundSizeChanged = true;
14349        }
14350        return changed;
14351    }
14352
14353    private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) {
14354        onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14355        if (mOverlay != null) {
14356            mOverlay.getOverlayView().setRight(newWidth);
14357            mOverlay.getOverlayView().setBottom(newHeight);
14358        }
14359    }
14360
14361    /**
14362     * Finalize inflating a view from XML.  This is called as the last phase
14363     * of inflation, after all child views have been added.
14364     *
14365     * <p>Even if the subclass overrides onFinishInflate, they should always be
14366     * sure to call the super method, so that we get called.
14367     */
14368    protected void onFinishInflate() {
14369    }
14370
14371    /**
14372     * Returns the resources associated with this view.
14373     *
14374     * @return Resources object.
14375     */
14376    public Resources getResources() {
14377        return mResources;
14378    }
14379
14380    /**
14381     * Invalidates the specified Drawable.
14382     *
14383     * @param drawable the drawable to invalidate
14384     */
14385    public void invalidateDrawable(Drawable drawable) {
14386        if (verifyDrawable(drawable)) {
14387            final Rect dirty = drawable.getBounds();
14388            final int scrollX = mScrollX;
14389            final int scrollY = mScrollY;
14390
14391            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14392                    dirty.right + scrollX, dirty.bottom + scrollY);
14393        }
14394    }
14395
14396    /**
14397     * Schedules an action on a drawable to occur at a specified time.
14398     *
14399     * @param who the recipient of the action
14400     * @param what the action to run on the drawable
14401     * @param when the time at which the action must occur. Uses the
14402     *        {@link SystemClock#uptimeMillis} timebase.
14403     */
14404    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14405        if (verifyDrawable(who) && what != null) {
14406            final long delay = when - SystemClock.uptimeMillis();
14407            if (mAttachInfo != null) {
14408                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14409                        Choreographer.CALLBACK_ANIMATION, what, who,
14410                        Choreographer.subtractFrameDelay(delay));
14411            } else {
14412                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14413            }
14414        }
14415    }
14416
14417    /**
14418     * Cancels a scheduled action on a drawable.
14419     *
14420     * @param who the recipient of the action
14421     * @param what the action to cancel
14422     */
14423    public void unscheduleDrawable(Drawable who, Runnable what) {
14424        if (verifyDrawable(who) && what != null) {
14425            if (mAttachInfo != null) {
14426                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14427                        Choreographer.CALLBACK_ANIMATION, what, who);
14428            } else {
14429                ViewRootImpl.getRunQueue().removeCallbacks(what);
14430            }
14431        }
14432    }
14433
14434    /**
14435     * Unschedule any events associated with the given Drawable.  This can be
14436     * used when selecting a new Drawable into a view, so that the previous
14437     * one is completely unscheduled.
14438     *
14439     * @param who The Drawable to unschedule.
14440     *
14441     * @see #drawableStateChanged
14442     */
14443    public void unscheduleDrawable(Drawable who) {
14444        if (mAttachInfo != null && who != null) {
14445            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14446                    Choreographer.CALLBACK_ANIMATION, null, who);
14447        }
14448    }
14449
14450    /**
14451     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14452     * that the View directionality can and will be resolved before its Drawables.
14453     *
14454     * Will call {@link View#onResolveDrawables} when resolution is done.
14455     *
14456     * @hide
14457     */
14458    protected void resolveDrawables() {
14459        if (canResolveLayoutDirection()) {
14460            if (mBackground != null) {
14461                mBackground.setLayoutDirection(getLayoutDirection());
14462            }
14463            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14464            onResolveDrawables(getLayoutDirection());
14465        }
14466    }
14467
14468    /**
14469     * Called when layout direction has been resolved.
14470     *
14471     * The default implementation does nothing.
14472     *
14473     * @param layoutDirection The resolved layout direction.
14474     *
14475     * @see #LAYOUT_DIRECTION_LTR
14476     * @see #LAYOUT_DIRECTION_RTL
14477     *
14478     * @hide
14479     */
14480    public void onResolveDrawables(int layoutDirection) {
14481    }
14482
14483    /**
14484     * @hide
14485     */
14486    protected void resetResolvedDrawables() {
14487        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14488    }
14489
14490    private boolean isDrawablesResolved() {
14491        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14492    }
14493
14494    /**
14495     * If your view subclass is displaying its own Drawable objects, it should
14496     * override this function and return true for any Drawable it is
14497     * displaying.  This allows animations for those drawables to be
14498     * scheduled.
14499     *
14500     * <p>Be sure to call through to the super class when overriding this
14501     * function.
14502     *
14503     * @param who The Drawable to verify.  Return true if it is one you are
14504     *            displaying, else return the result of calling through to the
14505     *            super class.
14506     *
14507     * @return boolean If true than the Drawable is being displayed in the
14508     *         view; else false and it is not allowed to animate.
14509     *
14510     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14511     * @see #drawableStateChanged()
14512     */
14513    protected boolean verifyDrawable(Drawable who) {
14514        return who == mBackground;
14515    }
14516
14517    /**
14518     * This function is called whenever the state of the view changes in such
14519     * a way that it impacts the state of drawables being shown.
14520     *
14521     * <p>Be sure to call through to the superclass when overriding this
14522     * function.
14523     *
14524     * @see Drawable#setState(int[])
14525     */
14526    protected void drawableStateChanged() {
14527        Drawable d = mBackground;
14528        if (d != null && d.isStateful()) {
14529            d.setState(getDrawableState());
14530        }
14531    }
14532
14533    /**
14534     * Call this to force a view to update its drawable state. This will cause
14535     * drawableStateChanged to be called on this view. Views that are interested
14536     * in the new state should call getDrawableState.
14537     *
14538     * @see #drawableStateChanged
14539     * @see #getDrawableState
14540     */
14541    public void refreshDrawableState() {
14542        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14543        drawableStateChanged();
14544
14545        ViewParent parent = mParent;
14546        if (parent != null) {
14547            parent.childDrawableStateChanged(this);
14548        }
14549    }
14550
14551    /**
14552     * Return an array of resource IDs of the drawable states representing the
14553     * current state of the view.
14554     *
14555     * @return The current drawable state
14556     *
14557     * @see Drawable#setState(int[])
14558     * @see #drawableStateChanged()
14559     * @see #onCreateDrawableState(int)
14560     */
14561    public final int[] getDrawableState() {
14562        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14563            return mDrawableState;
14564        } else {
14565            mDrawableState = onCreateDrawableState(0);
14566            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14567            return mDrawableState;
14568        }
14569    }
14570
14571    /**
14572     * Generate the new {@link android.graphics.drawable.Drawable} state for
14573     * this view. This is called by the view
14574     * system when the cached Drawable state is determined to be invalid.  To
14575     * retrieve the current state, you should use {@link #getDrawableState}.
14576     *
14577     * @param extraSpace if non-zero, this is the number of extra entries you
14578     * would like in the returned array in which you can place your own
14579     * states.
14580     *
14581     * @return Returns an array holding the current {@link Drawable} state of
14582     * the view.
14583     *
14584     * @see #mergeDrawableStates(int[], int[])
14585     */
14586    protected int[] onCreateDrawableState(int extraSpace) {
14587        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14588                mParent instanceof View) {
14589            return ((View) mParent).onCreateDrawableState(extraSpace);
14590        }
14591
14592        int[] drawableState;
14593
14594        int privateFlags = mPrivateFlags;
14595
14596        int viewStateIndex = 0;
14597        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14598        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14599        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14600        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14601        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14602        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14603        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14604                HardwareRenderer.isAvailable()) {
14605            // This is set if HW acceleration is requested, even if the current
14606            // process doesn't allow it.  This is just to allow app preview
14607            // windows to better match their app.
14608            viewStateIndex |= VIEW_STATE_ACCELERATED;
14609        }
14610        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14611
14612        final int privateFlags2 = mPrivateFlags2;
14613        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14614        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14615
14616        drawableState = VIEW_STATE_SETS[viewStateIndex];
14617
14618        //noinspection ConstantIfStatement
14619        if (false) {
14620            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14621            Log.i("View", toString()
14622                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14623                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14624                    + " fo=" + hasFocus()
14625                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14626                    + " wf=" + hasWindowFocus()
14627                    + ": " + Arrays.toString(drawableState));
14628        }
14629
14630        if (extraSpace == 0) {
14631            return drawableState;
14632        }
14633
14634        final int[] fullState;
14635        if (drawableState != null) {
14636            fullState = new int[drawableState.length + extraSpace];
14637            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14638        } else {
14639            fullState = new int[extraSpace];
14640        }
14641
14642        return fullState;
14643    }
14644
14645    /**
14646     * Merge your own state values in <var>additionalState</var> into the base
14647     * state values <var>baseState</var> that were returned by
14648     * {@link #onCreateDrawableState(int)}.
14649     *
14650     * @param baseState The base state values returned by
14651     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14652     * own additional state values.
14653     *
14654     * @param additionalState The additional state values you would like
14655     * added to <var>baseState</var>; this array is not modified.
14656     *
14657     * @return As a convenience, the <var>baseState</var> array you originally
14658     * passed into the function is returned.
14659     *
14660     * @see #onCreateDrawableState(int)
14661     */
14662    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14663        final int N = baseState.length;
14664        int i = N - 1;
14665        while (i >= 0 && baseState[i] == 0) {
14666            i--;
14667        }
14668        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14669        return baseState;
14670    }
14671
14672    /**
14673     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14674     * on all Drawable objects associated with this view.
14675     */
14676    public void jumpDrawablesToCurrentState() {
14677        if (mBackground != null) {
14678            mBackground.jumpToCurrentState();
14679        }
14680    }
14681
14682    /**
14683     * Sets the background color for this view.
14684     * @param color the color of the background
14685     */
14686    @RemotableViewMethod
14687    public void setBackgroundColor(int color) {
14688        if (mBackground instanceof ColorDrawable) {
14689            ((ColorDrawable) mBackground.mutate()).setColor(color);
14690            computeOpaqueFlags();
14691            mBackgroundResource = 0;
14692        } else {
14693            setBackground(new ColorDrawable(color));
14694        }
14695    }
14696
14697    /**
14698     * Set the background to a given resource. The resource should refer to
14699     * a Drawable object or 0 to remove the background.
14700     * @param resid The identifier of the resource.
14701     *
14702     * @attr ref android.R.styleable#View_background
14703     */
14704    @RemotableViewMethod
14705    public void setBackgroundResource(int resid) {
14706        if (resid != 0 && resid == mBackgroundResource) {
14707            return;
14708        }
14709
14710        Drawable d= null;
14711        if (resid != 0) {
14712            d = mResources.getDrawable(resid);
14713        }
14714        setBackground(d);
14715
14716        mBackgroundResource = resid;
14717    }
14718
14719    /**
14720     * Set the background to a given Drawable, or remove the background. If the
14721     * background has padding, this View's padding is set to the background's
14722     * padding. However, when a background is removed, this View's padding isn't
14723     * touched. If setting the padding is desired, please use
14724     * {@link #setPadding(int, int, int, int)}.
14725     *
14726     * @param background The Drawable to use as the background, or null to remove the
14727     *        background
14728     */
14729    public void setBackground(Drawable background) {
14730        //noinspection deprecation
14731        setBackgroundDrawable(background);
14732    }
14733
14734    /**
14735     * @deprecated use {@link #setBackground(Drawable)} instead
14736     */
14737    @Deprecated
14738    public void setBackgroundDrawable(Drawable background) {
14739        computeOpaqueFlags();
14740
14741        if (background == mBackground) {
14742            return;
14743        }
14744
14745        boolean requestLayout = false;
14746
14747        mBackgroundResource = 0;
14748
14749        /*
14750         * Regardless of whether we're setting a new background or not, we want
14751         * to clear the previous drawable.
14752         */
14753        if (mBackground != null) {
14754            mBackground.setCallback(null);
14755            unscheduleDrawable(mBackground);
14756        }
14757
14758        if (background != null) {
14759            Rect padding = sThreadLocal.get();
14760            if (padding == null) {
14761                padding = new Rect();
14762                sThreadLocal.set(padding);
14763            }
14764            resetResolvedDrawables();
14765            background.setLayoutDirection(getLayoutDirection());
14766            if (background.getPadding(padding)) {
14767                resetResolvedPadding();
14768                switch (background.getLayoutDirection()) {
14769                    case LAYOUT_DIRECTION_RTL:
14770                        mUserPaddingLeftInitial = padding.right;
14771                        mUserPaddingRightInitial = padding.left;
14772                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14773                        break;
14774                    case LAYOUT_DIRECTION_LTR:
14775                    default:
14776                        mUserPaddingLeftInitial = padding.left;
14777                        mUserPaddingRightInitial = padding.right;
14778                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14779                }
14780            }
14781
14782            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14783            // if it has a different minimum size, we should layout again
14784            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14785                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14786                requestLayout = true;
14787            }
14788
14789            background.setCallback(this);
14790            if (background.isStateful()) {
14791                background.setState(getDrawableState());
14792            }
14793            background.setVisible(getVisibility() == VISIBLE, false);
14794            mBackground = background;
14795
14796            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14797                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14798                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14799                requestLayout = true;
14800            }
14801        } else {
14802            /* Remove the background */
14803            mBackground = null;
14804
14805            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14806                /*
14807                 * This view ONLY drew the background before and we're removing
14808                 * the background, so now it won't draw anything
14809                 * (hence we SKIP_DRAW)
14810                 */
14811                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14812                mPrivateFlags |= PFLAG_SKIP_DRAW;
14813            }
14814
14815            /*
14816             * When the background is set, we try to apply its padding to this
14817             * View. When the background is removed, we don't touch this View's
14818             * padding. This is noted in the Javadocs. Hence, we don't need to
14819             * requestLayout(), the invalidate() below is sufficient.
14820             */
14821
14822            // The old background's minimum size could have affected this
14823            // View's layout, so let's requestLayout
14824            requestLayout = true;
14825        }
14826
14827        computeOpaqueFlags();
14828
14829        if (requestLayout) {
14830            requestLayout();
14831        }
14832
14833        mBackgroundSizeChanged = true;
14834        invalidate(true);
14835    }
14836
14837    /**
14838     * Gets the background drawable
14839     *
14840     * @return The drawable used as the background for this view, if any.
14841     *
14842     * @see #setBackground(Drawable)
14843     *
14844     * @attr ref android.R.styleable#View_background
14845     */
14846    public Drawable getBackground() {
14847        return mBackground;
14848    }
14849
14850    /**
14851     * Sets the padding. The view may add on the space required to display
14852     * the scrollbars, depending on the style and visibility of the scrollbars.
14853     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14854     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14855     * from the values set in this call.
14856     *
14857     * @attr ref android.R.styleable#View_padding
14858     * @attr ref android.R.styleable#View_paddingBottom
14859     * @attr ref android.R.styleable#View_paddingLeft
14860     * @attr ref android.R.styleable#View_paddingRight
14861     * @attr ref android.R.styleable#View_paddingTop
14862     * @param left the left padding in pixels
14863     * @param top the top padding in pixels
14864     * @param right the right padding in pixels
14865     * @param bottom the bottom padding in pixels
14866     */
14867    public void setPadding(int left, int top, int right, int bottom) {
14868        resetResolvedPadding();
14869
14870        mUserPaddingStart = UNDEFINED_PADDING;
14871        mUserPaddingEnd = UNDEFINED_PADDING;
14872
14873        mUserPaddingLeftInitial = left;
14874        mUserPaddingRightInitial = right;
14875
14876        internalSetPadding(left, top, right, bottom);
14877    }
14878
14879    /**
14880     * @hide
14881     */
14882    protected void internalSetPadding(int left, int top, int right, int bottom) {
14883        mUserPaddingLeft = left;
14884        mUserPaddingRight = right;
14885        mUserPaddingBottom = bottom;
14886
14887        final int viewFlags = mViewFlags;
14888        boolean changed = false;
14889
14890        // Common case is there are no scroll bars.
14891        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14892            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14893                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14894                        ? 0 : getVerticalScrollbarWidth();
14895                switch (mVerticalScrollbarPosition) {
14896                    case SCROLLBAR_POSITION_DEFAULT:
14897                        if (isLayoutRtl()) {
14898                            left += offset;
14899                        } else {
14900                            right += offset;
14901                        }
14902                        break;
14903                    case SCROLLBAR_POSITION_RIGHT:
14904                        right += offset;
14905                        break;
14906                    case SCROLLBAR_POSITION_LEFT:
14907                        left += offset;
14908                        break;
14909                }
14910            }
14911            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14912                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14913                        ? 0 : getHorizontalScrollbarHeight();
14914            }
14915        }
14916
14917        if (mPaddingLeft != left) {
14918            changed = true;
14919            mPaddingLeft = left;
14920        }
14921        if (mPaddingTop != top) {
14922            changed = true;
14923            mPaddingTop = top;
14924        }
14925        if (mPaddingRight != right) {
14926            changed = true;
14927            mPaddingRight = right;
14928        }
14929        if (mPaddingBottom != bottom) {
14930            changed = true;
14931            mPaddingBottom = bottom;
14932        }
14933
14934        if (changed) {
14935            requestLayout();
14936        }
14937    }
14938
14939    /**
14940     * Sets the relative padding. The view may add on the space required to display
14941     * the scrollbars, depending on the style and visibility of the scrollbars.
14942     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14943     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14944     * from the values set in this call.
14945     *
14946     * @attr ref android.R.styleable#View_padding
14947     * @attr ref android.R.styleable#View_paddingBottom
14948     * @attr ref android.R.styleable#View_paddingStart
14949     * @attr ref android.R.styleable#View_paddingEnd
14950     * @attr ref android.R.styleable#View_paddingTop
14951     * @param start the start padding in pixels
14952     * @param top the top padding in pixels
14953     * @param end the end padding in pixels
14954     * @param bottom the bottom padding in pixels
14955     */
14956    public void setPaddingRelative(int start, int top, int end, int bottom) {
14957        resetResolvedPadding();
14958
14959        mUserPaddingStart = start;
14960        mUserPaddingEnd = end;
14961
14962        switch(getLayoutDirection()) {
14963            case LAYOUT_DIRECTION_RTL:
14964                mUserPaddingLeftInitial = end;
14965                mUserPaddingRightInitial = start;
14966                internalSetPadding(end, top, start, bottom);
14967                break;
14968            case LAYOUT_DIRECTION_LTR:
14969            default:
14970                mUserPaddingLeftInitial = start;
14971                mUserPaddingRightInitial = end;
14972                internalSetPadding(start, top, end, bottom);
14973        }
14974    }
14975
14976    /**
14977     * Returns the top padding of this view.
14978     *
14979     * @return the top padding in pixels
14980     */
14981    public int getPaddingTop() {
14982        return mPaddingTop;
14983    }
14984
14985    /**
14986     * Returns the bottom padding of this view. If there are inset and enabled
14987     * scrollbars, this value may include the space required to display the
14988     * scrollbars as well.
14989     *
14990     * @return the bottom padding in pixels
14991     */
14992    public int getPaddingBottom() {
14993        return mPaddingBottom;
14994    }
14995
14996    /**
14997     * Returns the left padding of this view. If there are inset and enabled
14998     * scrollbars, this value may include the space required to display the
14999     * scrollbars as well.
15000     *
15001     * @return the left padding in pixels
15002     */
15003    public int getPaddingLeft() {
15004        if (!isPaddingResolved()) {
15005            resolvePadding();
15006        }
15007        return mPaddingLeft;
15008    }
15009
15010    /**
15011     * Returns the start padding of this view depending on its resolved layout direction.
15012     * If there are inset and enabled scrollbars, this value may include the space
15013     * required to display the scrollbars as well.
15014     *
15015     * @return the start padding in pixels
15016     */
15017    public int getPaddingStart() {
15018        if (!isPaddingResolved()) {
15019            resolvePadding();
15020        }
15021        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15022                mPaddingRight : mPaddingLeft;
15023    }
15024
15025    /**
15026     * Returns the right padding of this view. If there are inset and enabled
15027     * scrollbars, this value may include the space required to display the
15028     * scrollbars as well.
15029     *
15030     * @return the right padding in pixels
15031     */
15032    public int getPaddingRight() {
15033        if (!isPaddingResolved()) {
15034            resolvePadding();
15035        }
15036        return mPaddingRight;
15037    }
15038
15039    /**
15040     * Returns the end padding of this view depending on its resolved layout direction.
15041     * If there are inset and enabled scrollbars, this value may include the space
15042     * required to display the scrollbars as well.
15043     *
15044     * @return the end padding in pixels
15045     */
15046    public int getPaddingEnd() {
15047        if (!isPaddingResolved()) {
15048            resolvePadding();
15049        }
15050        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
15051                mPaddingLeft : mPaddingRight;
15052    }
15053
15054    /**
15055     * Return if the padding as been set thru relative values
15056     * {@link #setPaddingRelative(int, int, int, int)} or thru
15057     * @attr ref android.R.styleable#View_paddingStart or
15058     * @attr ref android.R.styleable#View_paddingEnd
15059     *
15060     * @return true if the padding is relative or false if it is not.
15061     */
15062    public boolean isPaddingRelative() {
15063        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15064    }
15065
15066    Insets computeOpticalInsets() {
15067        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15068    }
15069
15070    /**
15071     * @hide
15072     */
15073    public void resetPaddingToInitialValues() {
15074        if (isRtlCompatibilityMode()) {
15075            mPaddingLeft = mUserPaddingLeftInitial;
15076            mPaddingRight = mUserPaddingRightInitial;
15077            return;
15078        }
15079        if (isLayoutRtl()) {
15080            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15081            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15082        } else {
15083            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15084            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15085        }
15086    }
15087
15088    /**
15089     * @hide
15090     */
15091    public Insets getOpticalInsets() {
15092        if (mLayoutInsets == null) {
15093            mLayoutInsets = computeOpticalInsets();
15094        }
15095        return mLayoutInsets;
15096    }
15097
15098    /**
15099     * Changes the selection state of this view. A view can be selected or not.
15100     * Note that selection is not the same as focus. Views are typically
15101     * selected in the context of an AdapterView like ListView or GridView;
15102     * the selected view is the view that is highlighted.
15103     *
15104     * @param selected true if the view must be selected, false otherwise
15105     */
15106    public void setSelected(boolean selected) {
15107        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15108            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15109            if (!selected) resetPressedState();
15110            invalidate(true);
15111            refreshDrawableState();
15112            dispatchSetSelected(selected);
15113            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
15114                notifyAccessibilityStateChanged();
15115            }
15116        }
15117    }
15118
15119    /**
15120     * Dispatch setSelected to all of this View's children.
15121     *
15122     * @see #setSelected(boolean)
15123     *
15124     * @param selected The new selected state
15125     */
15126    protected void dispatchSetSelected(boolean selected) {
15127    }
15128
15129    /**
15130     * Indicates the selection state of this view.
15131     *
15132     * @return true if the view is selected, false otherwise
15133     */
15134    @ViewDebug.ExportedProperty
15135    public boolean isSelected() {
15136        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15137    }
15138
15139    /**
15140     * Changes the activated state of this view. A view can be activated or not.
15141     * Note that activation is not the same as selection.  Selection is
15142     * a transient property, representing the view (hierarchy) the user is
15143     * currently interacting with.  Activation is a longer-term state that the
15144     * user can move views in and out of.  For example, in a list view with
15145     * single or multiple selection enabled, the views in the current selection
15146     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15147     * here.)  The activated state is propagated down to children of the view it
15148     * is set on.
15149     *
15150     * @param activated true if the view must be activated, false otherwise
15151     */
15152    public void setActivated(boolean activated) {
15153        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15154            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15155            invalidate(true);
15156            refreshDrawableState();
15157            dispatchSetActivated(activated);
15158        }
15159    }
15160
15161    /**
15162     * Dispatch setActivated to all of this View's children.
15163     *
15164     * @see #setActivated(boolean)
15165     *
15166     * @param activated The new activated state
15167     */
15168    protected void dispatchSetActivated(boolean activated) {
15169    }
15170
15171    /**
15172     * Indicates the activation state of this view.
15173     *
15174     * @return true if the view is activated, false otherwise
15175     */
15176    @ViewDebug.ExportedProperty
15177    public boolean isActivated() {
15178        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15179    }
15180
15181    /**
15182     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15183     * observer can be used to get notifications when global events, like
15184     * layout, happen.
15185     *
15186     * The returned ViewTreeObserver observer is not guaranteed to remain
15187     * valid for the lifetime of this View. If the caller of this method keeps
15188     * a long-lived reference to ViewTreeObserver, it should always check for
15189     * the return value of {@link ViewTreeObserver#isAlive()}.
15190     *
15191     * @return The ViewTreeObserver for this view's hierarchy.
15192     */
15193    public ViewTreeObserver getViewTreeObserver() {
15194        if (mAttachInfo != null) {
15195            return mAttachInfo.mTreeObserver;
15196        }
15197        if (mFloatingTreeObserver == null) {
15198            mFloatingTreeObserver = new ViewTreeObserver();
15199        }
15200        return mFloatingTreeObserver;
15201    }
15202
15203    /**
15204     * <p>Finds the topmost view in the current view hierarchy.</p>
15205     *
15206     * @return the topmost view containing this view
15207     */
15208    public View getRootView() {
15209        if (mAttachInfo != null) {
15210            final View v = mAttachInfo.mRootView;
15211            if (v != null) {
15212                return v;
15213            }
15214        }
15215
15216        View parent = this;
15217
15218        while (parent.mParent != null && parent.mParent instanceof View) {
15219            parent = (View) parent.mParent;
15220        }
15221
15222        return parent;
15223    }
15224
15225    /**
15226     * <p>Computes the coordinates of this view on the screen. The argument
15227     * must be an array of two integers. After the method returns, the array
15228     * contains the x and y location in that order.</p>
15229     *
15230     * @param location an array of two integers in which to hold the coordinates
15231     */
15232    public void getLocationOnScreen(int[] location) {
15233        getLocationInWindow(location);
15234
15235        final AttachInfo info = mAttachInfo;
15236        if (info != null) {
15237            location[0] += info.mWindowLeft;
15238            location[1] += info.mWindowTop;
15239        }
15240    }
15241
15242    /**
15243     * <p>Computes the coordinates of this view in its window. The argument
15244     * must be an array of two integers. After the method returns, the array
15245     * contains the x and y location in that order.</p>
15246     *
15247     * @param location an array of two integers in which to hold the coordinates
15248     */
15249    public void getLocationInWindow(int[] location) {
15250        if (location == null || location.length < 2) {
15251            throw new IllegalArgumentException("location must be an array of two integers");
15252        }
15253
15254        if (mAttachInfo == null) {
15255            // When the view is not attached to a window, this method does not make sense
15256            location[0] = location[1] = 0;
15257            return;
15258        }
15259
15260        float[] position = mAttachInfo.mTmpTransformLocation;
15261        position[0] = position[1] = 0.0f;
15262
15263        if (!hasIdentityMatrix()) {
15264            getMatrix().mapPoints(position);
15265        }
15266
15267        position[0] += mLeft;
15268        position[1] += mTop;
15269
15270        ViewParent viewParent = mParent;
15271        while (viewParent instanceof View) {
15272            final View view = (View) viewParent;
15273
15274            position[0] -= view.mScrollX;
15275            position[1] -= view.mScrollY;
15276
15277            if (!view.hasIdentityMatrix()) {
15278                view.getMatrix().mapPoints(position);
15279            }
15280
15281            position[0] += view.mLeft;
15282            position[1] += view.mTop;
15283
15284            viewParent = view.mParent;
15285         }
15286
15287        if (viewParent instanceof ViewRootImpl) {
15288            // *cough*
15289            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15290            position[1] -= vr.mCurScrollY;
15291        }
15292
15293        location[0] = (int) (position[0] + 0.5f);
15294        location[1] = (int) (position[1] + 0.5f);
15295    }
15296
15297    /**
15298     * {@hide}
15299     * @param id the id of the view to be found
15300     * @return the view of the specified id, null if cannot be found
15301     */
15302    protected View findViewTraversal(int id) {
15303        if (id == mID) {
15304            return this;
15305        }
15306        return null;
15307    }
15308
15309    /**
15310     * {@hide}
15311     * @param tag the tag of the view to be found
15312     * @return the view of specified tag, null if cannot be found
15313     */
15314    protected View findViewWithTagTraversal(Object tag) {
15315        if (tag != null && tag.equals(mTag)) {
15316            return this;
15317        }
15318        return null;
15319    }
15320
15321    /**
15322     * {@hide}
15323     * @param predicate The predicate to evaluate.
15324     * @param childToSkip If not null, ignores this child during the recursive traversal.
15325     * @return The first view that matches the predicate or null.
15326     */
15327    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15328        if (predicate.apply(this)) {
15329            return this;
15330        }
15331        return null;
15332    }
15333
15334    /**
15335     * Look for a child view with the given id.  If this view has the given
15336     * id, return this view.
15337     *
15338     * @param id The id to search for.
15339     * @return The view that has the given id in the hierarchy or null
15340     */
15341    public final View findViewById(int id) {
15342        if (id < 0) {
15343            return null;
15344        }
15345        return findViewTraversal(id);
15346    }
15347
15348    /**
15349     * Finds a view by its unuque and stable accessibility id.
15350     *
15351     * @param accessibilityId The searched accessibility id.
15352     * @return The found view.
15353     */
15354    final View findViewByAccessibilityId(int accessibilityId) {
15355        if (accessibilityId < 0) {
15356            return null;
15357        }
15358        return findViewByAccessibilityIdTraversal(accessibilityId);
15359    }
15360
15361    /**
15362     * Performs the traversal to find a view by its unuque and stable accessibility id.
15363     *
15364     * <strong>Note:</strong>This method does not stop at the root namespace
15365     * boundary since the user can touch the screen at an arbitrary location
15366     * potentially crossing the root namespace bounday which will send an
15367     * accessibility event to accessibility services and they should be able
15368     * to obtain the event source. Also accessibility ids are guaranteed to be
15369     * unique in the window.
15370     *
15371     * @param accessibilityId The accessibility id.
15372     * @return The found view.
15373     */
15374    View findViewByAccessibilityIdTraversal(int accessibilityId) {
15375        if (getAccessibilityViewId() == accessibilityId) {
15376            return this;
15377        }
15378        return null;
15379    }
15380
15381    /**
15382     * Look for a child view with the given tag.  If this view has the given
15383     * tag, return this view.
15384     *
15385     * @param tag The tag to search for, using "tag.equals(getTag())".
15386     * @return The View that has the given tag in the hierarchy or null
15387     */
15388    public final View findViewWithTag(Object tag) {
15389        if (tag == null) {
15390            return null;
15391        }
15392        return findViewWithTagTraversal(tag);
15393    }
15394
15395    /**
15396     * {@hide}
15397     * Look for a child view that matches the specified predicate.
15398     * If this view matches the predicate, return this view.
15399     *
15400     * @param predicate The predicate to evaluate.
15401     * @return The first view that matches the predicate or null.
15402     */
15403    public final View findViewByPredicate(Predicate<View> predicate) {
15404        return findViewByPredicateTraversal(predicate, null);
15405    }
15406
15407    /**
15408     * {@hide}
15409     * Look for a child view that matches the specified predicate,
15410     * starting with the specified view and its descendents and then
15411     * recusively searching the ancestors and siblings of that view
15412     * until this view is reached.
15413     *
15414     * This method is useful in cases where the predicate does not match
15415     * a single unique view (perhaps multiple views use the same id)
15416     * and we are trying to find the view that is "closest" in scope to the
15417     * starting view.
15418     *
15419     * @param start The view to start from.
15420     * @param predicate The predicate to evaluate.
15421     * @return The first view that matches the predicate or null.
15422     */
15423    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15424        View childToSkip = null;
15425        for (;;) {
15426            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15427            if (view != null || start == this) {
15428                return view;
15429            }
15430
15431            ViewParent parent = start.getParent();
15432            if (parent == null || !(parent instanceof View)) {
15433                return null;
15434            }
15435
15436            childToSkip = start;
15437            start = (View) parent;
15438        }
15439    }
15440
15441    /**
15442     * Sets the identifier for this view. The identifier does not have to be
15443     * unique in this view's hierarchy. The identifier should be a positive
15444     * number.
15445     *
15446     * @see #NO_ID
15447     * @see #getId()
15448     * @see #findViewById(int)
15449     *
15450     * @param id a number used to identify the view
15451     *
15452     * @attr ref android.R.styleable#View_id
15453     */
15454    public void setId(int id) {
15455        mID = id;
15456        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15457            mID = generateViewId();
15458        }
15459    }
15460
15461    /**
15462     * {@hide}
15463     *
15464     * @param isRoot true if the view belongs to the root namespace, false
15465     *        otherwise
15466     */
15467    public void setIsRootNamespace(boolean isRoot) {
15468        if (isRoot) {
15469            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15470        } else {
15471            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15472        }
15473    }
15474
15475    /**
15476     * {@hide}
15477     *
15478     * @return true if the view belongs to the root namespace, false otherwise
15479     */
15480    public boolean isRootNamespace() {
15481        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15482    }
15483
15484    /**
15485     * Returns this view's identifier.
15486     *
15487     * @return a positive integer used to identify the view or {@link #NO_ID}
15488     *         if the view has no ID
15489     *
15490     * @see #setId(int)
15491     * @see #findViewById(int)
15492     * @attr ref android.R.styleable#View_id
15493     */
15494    @ViewDebug.CapturedViewProperty
15495    public int getId() {
15496        return mID;
15497    }
15498
15499    /**
15500     * Returns this view's tag.
15501     *
15502     * @return the Object stored in this view as a tag
15503     *
15504     * @see #setTag(Object)
15505     * @see #getTag(int)
15506     */
15507    @ViewDebug.ExportedProperty
15508    public Object getTag() {
15509        return mTag;
15510    }
15511
15512    /**
15513     * Sets the tag associated with this view. A tag can be used to mark
15514     * a view in its hierarchy and does not have to be unique within the
15515     * hierarchy. Tags can also be used to store data within a view without
15516     * resorting to another data structure.
15517     *
15518     * @param tag an Object to tag the view with
15519     *
15520     * @see #getTag()
15521     * @see #setTag(int, Object)
15522     */
15523    public void setTag(final Object tag) {
15524        mTag = tag;
15525    }
15526
15527    /**
15528     * Returns the tag associated with this view and the specified key.
15529     *
15530     * @param key The key identifying the tag
15531     *
15532     * @return the Object stored in this view as a tag
15533     *
15534     * @see #setTag(int, Object)
15535     * @see #getTag()
15536     */
15537    public Object getTag(int key) {
15538        if (mKeyedTags != null) return mKeyedTags.get(key);
15539        return null;
15540    }
15541
15542    /**
15543     * Sets a tag associated with this view and a key. A tag can be used
15544     * to mark a view in its hierarchy and does not have to be unique within
15545     * the hierarchy. Tags can also be used to store data within a view
15546     * without resorting to another data structure.
15547     *
15548     * The specified key should be an id declared in the resources of the
15549     * application to ensure it is unique (see the <a
15550     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15551     * Keys identified as belonging to
15552     * the Android framework or not associated with any package will cause
15553     * an {@link IllegalArgumentException} to be thrown.
15554     *
15555     * @param key The key identifying the tag
15556     * @param tag An Object to tag the view with
15557     *
15558     * @throws IllegalArgumentException If they specified key is not valid
15559     *
15560     * @see #setTag(Object)
15561     * @see #getTag(int)
15562     */
15563    public void setTag(int key, final Object tag) {
15564        // If the package id is 0x00 or 0x01, it's either an undefined package
15565        // or a framework id
15566        if ((key >>> 24) < 2) {
15567            throw new IllegalArgumentException("The key must be an application-specific "
15568                    + "resource id.");
15569        }
15570
15571        setKeyedTag(key, tag);
15572    }
15573
15574    /**
15575     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15576     * framework id.
15577     *
15578     * @hide
15579     */
15580    public void setTagInternal(int key, Object tag) {
15581        if ((key >>> 24) != 0x1) {
15582            throw new IllegalArgumentException("The key must be a framework-specific "
15583                    + "resource id.");
15584        }
15585
15586        setKeyedTag(key, tag);
15587    }
15588
15589    private void setKeyedTag(int key, Object tag) {
15590        if (mKeyedTags == null) {
15591            mKeyedTags = new SparseArray<Object>();
15592        }
15593
15594        mKeyedTags.put(key, tag);
15595    }
15596
15597    /**
15598     * Prints information about this view in the log output, with the tag
15599     * {@link #VIEW_LOG_TAG}.
15600     *
15601     * @hide
15602     */
15603    public void debug() {
15604        debug(0);
15605    }
15606
15607    /**
15608     * Prints information about this view in the log output, with the tag
15609     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15610     * indentation defined by the <code>depth</code>.
15611     *
15612     * @param depth the indentation level
15613     *
15614     * @hide
15615     */
15616    protected void debug(int depth) {
15617        String output = debugIndent(depth - 1);
15618
15619        output += "+ " + this;
15620        int id = getId();
15621        if (id != -1) {
15622            output += " (id=" + id + ")";
15623        }
15624        Object tag = getTag();
15625        if (tag != null) {
15626            output += " (tag=" + tag + ")";
15627        }
15628        Log.d(VIEW_LOG_TAG, output);
15629
15630        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15631            output = debugIndent(depth) + " FOCUSED";
15632            Log.d(VIEW_LOG_TAG, output);
15633        }
15634
15635        output = debugIndent(depth);
15636        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15637                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15638                + "} ";
15639        Log.d(VIEW_LOG_TAG, output);
15640
15641        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15642                || mPaddingBottom != 0) {
15643            output = debugIndent(depth);
15644            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15645                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15646            Log.d(VIEW_LOG_TAG, output);
15647        }
15648
15649        output = debugIndent(depth);
15650        output += "mMeasureWidth=" + mMeasuredWidth +
15651                " mMeasureHeight=" + mMeasuredHeight;
15652        Log.d(VIEW_LOG_TAG, output);
15653
15654        output = debugIndent(depth);
15655        if (mLayoutParams == null) {
15656            output += "BAD! no layout params";
15657        } else {
15658            output = mLayoutParams.debug(output);
15659        }
15660        Log.d(VIEW_LOG_TAG, output);
15661
15662        output = debugIndent(depth);
15663        output += "flags={";
15664        output += View.printFlags(mViewFlags);
15665        output += "}";
15666        Log.d(VIEW_LOG_TAG, output);
15667
15668        output = debugIndent(depth);
15669        output += "privateFlags={";
15670        output += View.printPrivateFlags(mPrivateFlags);
15671        output += "}";
15672        Log.d(VIEW_LOG_TAG, output);
15673    }
15674
15675    /**
15676     * Creates a string of whitespaces used for indentation.
15677     *
15678     * @param depth the indentation level
15679     * @return a String containing (depth * 2 + 3) * 2 white spaces
15680     *
15681     * @hide
15682     */
15683    protected static String debugIndent(int depth) {
15684        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15685        for (int i = 0; i < (depth * 2) + 3; i++) {
15686            spaces.append(' ').append(' ');
15687        }
15688        return spaces.toString();
15689    }
15690
15691    /**
15692     * <p>Return the offset of the widget's text baseline from the widget's top
15693     * boundary. If this widget does not support baseline alignment, this
15694     * method returns -1. </p>
15695     *
15696     * @return the offset of the baseline within the widget's bounds or -1
15697     *         if baseline alignment is not supported
15698     */
15699    @ViewDebug.ExportedProperty(category = "layout")
15700    public int getBaseline() {
15701        return -1;
15702    }
15703
15704    /**
15705     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15706     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15707     * a layout pass.
15708     *
15709     * @return whether the view hierarchy is currently undergoing a layout pass
15710     */
15711    public boolean isInLayout() {
15712        ViewRootImpl viewRoot = getViewRootImpl();
15713        return (viewRoot != null && viewRoot.isInLayout());
15714    }
15715
15716    /**
15717     * Call this when something has changed which has invalidated the
15718     * layout of this view. This will schedule a layout pass of the view
15719     * tree. This should not be called while the view hierarchy is currently in a layout
15720     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15721     * end of the current layout pass (and then layout will run again) or after the current
15722     * frame is drawn and the next layout occurs.
15723     *
15724     * <p>Subclasses which override this method should call the superclass method to
15725     * handle possible request-during-layout errors correctly.</p>
15726     */
15727    public void requestLayout() {
15728        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15729            // Only trigger request-during-layout logic if this is the view requesting it,
15730            // not the views in its parent hierarchy
15731            ViewRootImpl viewRoot = getViewRootImpl();
15732            if (viewRoot != null && viewRoot.isInLayout()) {
15733                if (!viewRoot.requestLayoutDuringLayout(this)) {
15734                    return;
15735                }
15736            }
15737            mAttachInfo.mViewRequestingLayout = this;
15738        }
15739
15740        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15741        mPrivateFlags |= PFLAG_INVALIDATED;
15742
15743        if (mParent != null && !mParent.isLayoutRequested()) {
15744            mParent.requestLayout();
15745        }
15746        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15747            mAttachInfo.mViewRequestingLayout = null;
15748        }
15749    }
15750
15751    /**
15752     * Forces this view to be laid out during the next layout pass.
15753     * This method does not call requestLayout() or forceLayout()
15754     * on the parent.
15755     */
15756    public void forceLayout() {
15757        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15758        mPrivateFlags |= PFLAG_INVALIDATED;
15759    }
15760
15761    /**
15762     * <p>
15763     * This is called to find out how big a view should be. The parent
15764     * supplies constraint information in the width and height parameters.
15765     * </p>
15766     *
15767     * <p>
15768     * The actual measurement work of a view is performed in
15769     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15770     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15771     * </p>
15772     *
15773     *
15774     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15775     *        parent
15776     * @param heightMeasureSpec Vertical space requirements as imposed by the
15777     *        parent
15778     *
15779     * @see #onMeasure(int, int)
15780     */
15781    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15782        boolean optical = isLayoutModeOptical(this);
15783        if (optical != isLayoutModeOptical(mParent)) {
15784            Insets insets = getOpticalInsets();
15785            int oWidth  = insets.left + insets.right;
15786            int oHeight = insets.top  + insets.bottom;
15787            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15788            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15789        }
15790        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15791                widthMeasureSpec != mOldWidthMeasureSpec ||
15792                heightMeasureSpec != mOldHeightMeasureSpec) {
15793
15794            // first clears the measured dimension flag
15795            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15796
15797            resolveRtlPropertiesIfNeeded();
15798
15799            // measure ourselves, this should set the measured dimension flag back
15800            onMeasure(widthMeasureSpec, heightMeasureSpec);
15801
15802            // flag not set, setMeasuredDimension() was not invoked, we raise
15803            // an exception to warn the developer
15804            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15805                throw new IllegalStateException("onMeasure() did not set the"
15806                        + " measured dimension by calling"
15807                        + " setMeasuredDimension()");
15808            }
15809
15810            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15811        }
15812
15813        mOldWidthMeasureSpec = widthMeasureSpec;
15814        mOldHeightMeasureSpec = heightMeasureSpec;
15815    }
15816
15817    /**
15818     * <p>
15819     * Measure the view and its content to determine the measured width and the
15820     * measured height. This method is invoked by {@link #measure(int, int)} and
15821     * should be overriden by subclasses to provide accurate and efficient
15822     * measurement of their contents.
15823     * </p>
15824     *
15825     * <p>
15826     * <strong>CONTRACT:</strong> When overriding this method, you
15827     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15828     * measured width and height of this view. Failure to do so will trigger an
15829     * <code>IllegalStateException</code>, thrown by
15830     * {@link #measure(int, int)}. Calling the superclass'
15831     * {@link #onMeasure(int, int)} is a valid use.
15832     * </p>
15833     *
15834     * <p>
15835     * The base class implementation of measure defaults to the background size,
15836     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15837     * override {@link #onMeasure(int, int)} to provide better measurements of
15838     * their content.
15839     * </p>
15840     *
15841     * <p>
15842     * If this method is overridden, it is the subclass's responsibility to make
15843     * sure the measured height and width are at least the view's minimum height
15844     * and width ({@link #getSuggestedMinimumHeight()} and
15845     * {@link #getSuggestedMinimumWidth()}).
15846     * </p>
15847     *
15848     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15849     *                         The requirements are encoded with
15850     *                         {@link android.view.View.MeasureSpec}.
15851     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15852     *                         The requirements are encoded with
15853     *                         {@link android.view.View.MeasureSpec}.
15854     *
15855     * @see #getMeasuredWidth()
15856     * @see #getMeasuredHeight()
15857     * @see #setMeasuredDimension(int, int)
15858     * @see #getSuggestedMinimumHeight()
15859     * @see #getSuggestedMinimumWidth()
15860     * @see android.view.View.MeasureSpec#getMode(int)
15861     * @see android.view.View.MeasureSpec#getSize(int)
15862     */
15863    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15864        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15865                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15866    }
15867
15868    /**
15869     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15870     * measured width and measured height. Failing to do so will trigger an
15871     * exception at measurement time.</p>
15872     *
15873     * @param measuredWidth The measured width of this view.  May be a complex
15874     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15875     * {@link #MEASURED_STATE_TOO_SMALL}.
15876     * @param measuredHeight The measured height of this view.  May be a complex
15877     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15878     * {@link #MEASURED_STATE_TOO_SMALL}.
15879     */
15880    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15881        boolean optical = isLayoutModeOptical(this);
15882        if (optical != isLayoutModeOptical(mParent)) {
15883            Insets insets = getOpticalInsets();
15884            int opticalWidth  = insets.left + insets.right;
15885            int opticalHeight = insets.top  + insets.bottom;
15886
15887            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
15888            measuredHeight += optical ? opticalHeight : -opticalHeight;
15889        }
15890        mMeasuredWidth = measuredWidth;
15891        mMeasuredHeight = measuredHeight;
15892
15893        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
15894    }
15895
15896    /**
15897     * Merge two states as returned by {@link #getMeasuredState()}.
15898     * @param curState The current state as returned from a view or the result
15899     * of combining multiple views.
15900     * @param newState The new view state to combine.
15901     * @return Returns a new integer reflecting the combination of the two
15902     * states.
15903     */
15904    public static int combineMeasuredStates(int curState, int newState) {
15905        return curState | newState;
15906    }
15907
15908    /**
15909     * Version of {@link #resolveSizeAndState(int, int, int)}
15910     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15911     */
15912    public static int resolveSize(int size, int measureSpec) {
15913        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15914    }
15915
15916    /**
15917     * Utility to reconcile a desired size and state, with constraints imposed
15918     * by a MeasureSpec.  Will take the desired size, unless a different size
15919     * is imposed by the constraints.  The returned value is a compound integer,
15920     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15921     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15922     * size is smaller than the size the view wants to be.
15923     *
15924     * @param size How big the view wants to be
15925     * @param measureSpec Constraints imposed by the parent
15926     * @return Size information bit mask as defined by
15927     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15928     */
15929    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15930        int result = size;
15931        int specMode = MeasureSpec.getMode(measureSpec);
15932        int specSize =  MeasureSpec.getSize(measureSpec);
15933        switch (specMode) {
15934        case MeasureSpec.UNSPECIFIED:
15935            result = size;
15936            break;
15937        case MeasureSpec.AT_MOST:
15938            if (specSize < size) {
15939                result = specSize | MEASURED_STATE_TOO_SMALL;
15940            } else {
15941                result = size;
15942            }
15943            break;
15944        case MeasureSpec.EXACTLY:
15945            result = specSize;
15946            break;
15947        }
15948        return result | (childMeasuredState&MEASURED_STATE_MASK);
15949    }
15950
15951    /**
15952     * Utility to return a default size. Uses the supplied size if the
15953     * MeasureSpec imposed no constraints. Will get larger if allowed
15954     * by the MeasureSpec.
15955     *
15956     * @param size Default size for this view
15957     * @param measureSpec Constraints imposed by the parent
15958     * @return The size this view should be.
15959     */
15960    public static int getDefaultSize(int size, int measureSpec) {
15961        int result = size;
15962        int specMode = MeasureSpec.getMode(measureSpec);
15963        int specSize = MeasureSpec.getSize(measureSpec);
15964
15965        switch (specMode) {
15966        case MeasureSpec.UNSPECIFIED:
15967            result = size;
15968            break;
15969        case MeasureSpec.AT_MOST:
15970        case MeasureSpec.EXACTLY:
15971            result = specSize;
15972            break;
15973        }
15974        return result;
15975    }
15976
15977    /**
15978     * Returns the suggested minimum height that the view should use. This
15979     * returns the maximum of the view's minimum height
15980     * and the background's minimum height
15981     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15982     * <p>
15983     * When being used in {@link #onMeasure(int, int)}, the caller should still
15984     * ensure the returned height is within the requirements of the parent.
15985     *
15986     * @return The suggested minimum height of the view.
15987     */
15988    protected int getSuggestedMinimumHeight() {
15989        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15990
15991    }
15992
15993    /**
15994     * Returns the suggested minimum width that the view should use. This
15995     * returns the maximum of the view's minimum width)
15996     * and the background's minimum width
15997     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15998     * <p>
15999     * When being used in {@link #onMeasure(int, int)}, the caller should still
16000     * ensure the returned width is within the requirements of the parent.
16001     *
16002     * @return The suggested minimum width of the view.
16003     */
16004    protected int getSuggestedMinimumWidth() {
16005        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
16006    }
16007
16008    /**
16009     * Returns the minimum height of the view.
16010     *
16011     * @return the minimum height the view will try to be.
16012     *
16013     * @see #setMinimumHeight(int)
16014     *
16015     * @attr ref android.R.styleable#View_minHeight
16016     */
16017    public int getMinimumHeight() {
16018        return mMinHeight;
16019    }
16020
16021    /**
16022     * Sets the minimum height of the view. It is not guaranteed the view will
16023     * be able to achieve this minimum height (for example, if its parent layout
16024     * constrains it with less available height).
16025     *
16026     * @param minHeight The minimum height the view will try to be.
16027     *
16028     * @see #getMinimumHeight()
16029     *
16030     * @attr ref android.R.styleable#View_minHeight
16031     */
16032    public void setMinimumHeight(int minHeight) {
16033        mMinHeight = minHeight;
16034        requestLayout();
16035    }
16036
16037    /**
16038     * Returns the minimum width of the view.
16039     *
16040     * @return the minimum width the view will try to be.
16041     *
16042     * @see #setMinimumWidth(int)
16043     *
16044     * @attr ref android.R.styleable#View_minWidth
16045     */
16046    public int getMinimumWidth() {
16047        return mMinWidth;
16048    }
16049
16050    /**
16051     * Sets the minimum width of the view. It is not guaranteed the view will
16052     * be able to achieve this minimum width (for example, if its parent layout
16053     * constrains it with less available width).
16054     *
16055     * @param minWidth The minimum width the view will try to be.
16056     *
16057     * @see #getMinimumWidth()
16058     *
16059     * @attr ref android.R.styleable#View_minWidth
16060     */
16061    public void setMinimumWidth(int minWidth) {
16062        mMinWidth = minWidth;
16063        requestLayout();
16064
16065    }
16066
16067    /**
16068     * Get the animation currently associated with this view.
16069     *
16070     * @return The animation that is currently playing or
16071     *         scheduled to play for this view.
16072     */
16073    public Animation getAnimation() {
16074        return mCurrentAnimation;
16075    }
16076
16077    /**
16078     * Start the specified animation now.
16079     *
16080     * @param animation the animation to start now
16081     */
16082    public void startAnimation(Animation animation) {
16083        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16084        setAnimation(animation);
16085        invalidateParentCaches();
16086        invalidate(true);
16087    }
16088
16089    /**
16090     * Cancels any animations for this view.
16091     */
16092    public void clearAnimation() {
16093        if (mCurrentAnimation != null) {
16094            mCurrentAnimation.detach();
16095        }
16096        mCurrentAnimation = null;
16097        invalidateParentIfNeeded();
16098    }
16099
16100    /**
16101     * Sets the next animation to play for this view.
16102     * If you want the animation to play immediately, use
16103     * {@link #startAnimation(android.view.animation.Animation)} instead.
16104     * This method provides allows fine-grained
16105     * control over the start time and invalidation, but you
16106     * must make sure that 1) the animation has a start time set, and
16107     * 2) the view's parent (which controls animations on its children)
16108     * will be invalidated when the animation is supposed to
16109     * start.
16110     *
16111     * @param animation The next animation, or null.
16112     */
16113    public void setAnimation(Animation animation) {
16114        mCurrentAnimation = animation;
16115
16116        if (animation != null) {
16117            // If the screen is off assume the animation start time is now instead of
16118            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16119            // would cause the animation to start when the screen turns back on
16120            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16121                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16122                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16123            }
16124            animation.reset();
16125        }
16126    }
16127
16128    /**
16129     * Invoked by a parent ViewGroup to notify the start of the animation
16130     * currently associated with this view. If you override this method,
16131     * always call super.onAnimationStart();
16132     *
16133     * @see #setAnimation(android.view.animation.Animation)
16134     * @see #getAnimation()
16135     */
16136    protected void onAnimationStart() {
16137        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16138    }
16139
16140    /**
16141     * Invoked by a parent ViewGroup to notify the end of the animation
16142     * currently associated with this view. If you override this method,
16143     * always call super.onAnimationEnd();
16144     *
16145     * @see #setAnimation(android.view.animation.Animation)
16146     * @see #getAnimation()
16147     */
16148    protected void onAnimationEnd() {
16149        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16150    }
16151
16152    /**
16153     * Invoked if there is a Transform that involves alpha. Subclass that can
16154     * draw themselves with the specified alpha should return true, and then
16155     * respect that alpha when their onDraw() is called. If this returns false
16156     * then the view may be redirected to draw into an offscreen buffer to
16157     * fulfill the request, which will look fine, but may be slower than if the
16158     * subclass handles it internally. The default implementation returns false.
16159     *
16160     * @param alpha The alpha (0..255) to apply to the view's drawing
16161     * @return true if the view can draw with the specified alpha.
16162     */
16163    protected boolean onSetAlpha(int alpha) {
16164        return false;
16165    }
16166
16167    /**
16168     * This is used by the RootView to perform an optimization when
16169     * the view hierarchy contains one or several SurfaceView.
16170     * SurfaceView is always considered transparent, but its children are not,
16171     * therefore all View objects remove themselves from the global transparent
16172     * region (passed as a parameter to this function).
16173     *
16174     * @param region The transparent region for this ViewAncestor (window).
16175     *
16176     * @return Returns true if the effective visibility of the view at this
16177     * point is opaque, regardless of the transparent region; returns false
16178     * if it is possible for underlying windows to be seen behind the view.
16179     *
16180     * {@hide}
16181     */
16182    public boolean gatherTransparentRegion(Region region) {
16183        final AttachInfo attachInfo = mAttachInfo;
16184        if (region != null && attachInfo != null) {
16185            final int pflags = mPrivateFlags;
16186            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16187                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16188                // remove it from the transparent region.
16189                final int[] location = attachInfo.mTransparentLocation;
16190                getLocationInWindow(location);
16191                region.op(location[0], location[1], location[0] + mRight - mLeft,
16192                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16193            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16194                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16195                // exists, so we remove the background drawable's non-transparent
16196                // parts from this transparent region.
16197                applyDrawableToTransparentRegion(mBackground, region);
16198            }
16199        }
16200        return true;
16201    }
16202
16203    /**
16204     * Play a sound effect for this view.
16205     *
16206     * <p>The framework will play sound effects for some built in actions, such as
16207     * clicking, but you may wish to play these effects in your widget,
16208     * for instance, for internal navigation.
16209     *
16210     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16211     * {@link #isSoundEffectsEnabled()} is true.
16212     *
16213     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16214     */
16215    public void playSoundEffect(int soundConstant) {
16216        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16217            return;
16218        }
16219        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16220    }
16221
16222    /**
16223     * BZZZTT!!1!
16224     *
16225     * <p>Provide haptic feedback to the user for this view.
16226     *
16227     * <p>The framework will provide haptic feedback for some built in actions,
16228     * such as long presses, but you may wish to provide feedback for your
16229     * own widget.
16230     *
16231     * <p>The feedback will only be performed if
16232     * {@link #isHapticFeedbackEnabled()} is true.
16233     *
16234     * @param feedbackConstant One of the constants defined in
16235     * {@link HapticFeedbackConstants}
16236     */
16237    public boolean performHapticFeedback(int feedbackConstant) {
16238        return performHapticFeedback(feedbackConstant, 0);
16239    }
16240
16241    /**
16242     * BZZZTT!!1!
16243     *
16244     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16245     *
16246     * @param feedbackConstant One of the constants defined in
16247     * {@link HapticFeedbackConstants}
16248     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16249     */
16250    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16251        if (mAttachInfo == null) {
16252            return false;
16253        }
16254        //noinspection SimplifiableIfStatement
16255        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16256                && !isHapticFeedbackEnabled()) {
16257            return false;
16258        }
16259        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16260                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16261    }
16262
16263    /**
16264     * Request that the visibility of the status bar or other screen/window
16265     * decorations be changed.
16266     *
16267     * <p>This method is used to put the over device UI into temporary modes
16268     * where the user's attention is focused more on the application content,
16269     * by dimming or hiding surrounding system affordances.  This is typically
16270     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16271     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16272     * to be placed behind the action bar (and with these flags other system
16273     * affordances) so that smooth transitions between hiding and showing them
16274     * can be done.
16275     *
16276     * <p>Two representative examples of the use of system UI visibility is
16277     * implementing a content browsing application (like a magazine reader)
16278     * and a video playing application.
16279     *
16280     * <p>The first code shows a typical implementation of a View in a content
16281     * browsing application.  In this implementation, the application goes
16282     * into a content-oriented mode by hiding the status bar and action bar,
16283     * and putting the navigation elements into lights out mode.  The user can
16284     * then interact with content while in this mode.  Such an application should
16285     * provide an easy way for the user to toggle out of the mode (such as to
16286     * check information in the status bar or access notifications).  In the
16287     * implementation here, this is done simply by tapping on the content.
16288     *
16289     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16290     *      content}
16291     *
16292     * <p>This second code sample shows a typical implementation of a View
16293     * in a video playing application.  In this situation, while the video is
16294     * playing the application would like to go into a complete full-screen mode,
16295     * to use as much of the display as possible for the video.  When in this state
16296     * the user can not interact with the application; the system intercepts
16297     * touching on the screen to pop the UI out of full screen mode.  See
16298     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16299     *
16300     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16301     *      content}
16302     *
16303     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16304     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16305     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16306     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16307     */
16308    public void setSystemUiVisibility(int visibility) {
16309        if (visibility != mSystemUiVisibility) {
16310            mSystemUiVisibility = visibility;
16311            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16312                mParent.recomputeViewAttributes(this);
16313            }
16314        }
16315    }
16316
16317    /**
16318     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16319     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16320     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16321     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16322     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16323     */
16324    public int getSystemUiVisibility() {
16325        return mSystemUiVisibility;
16326    }
16327
16328    /**
16329     * Returns the current system UI visibility that is currently set for
16330     * the entire window.  This is the combination of the
16331     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16332     * views in the window.
16333     */
16334    public int getWindowSystemUiVisibility() {
16335        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16336    }
16337
16338    /**
16339     * Override to find out when the window's requested system UI visibility
16340     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16341     * This is different from the callbacks recieved through
16342     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16343     * in that this is only telling you about the local request of the window,
16344     * not the actual values applied by the system.
16345     */
16346    public void onWindowSystemUiVisibilityChanged(int visible) {
16347    }
16348
16349    /**
16350     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16351     * the view hierarchy.
16352     */
16353    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16354        onWindowSystemUiVisibilityChanged(visible);
16355    }
16356
16357    /**
16358     * Set a listener to receive callbacks when the visibility of the system bar changes.
16359     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16360     */
16361    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16362        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16363        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16364            mParent.recomputeViewAttributes(this);
16365        }
16366    }
16367
16368    /**
16369     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16370     * the view hierarchy.
16371     */
16372    public void dispatchSystemUiVisibilityChanged(int visibility) {
16373        ListenerInfo li = mListenerInfo;
16374        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16375            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16376                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16377        }
16378    }
16379
16380    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16381        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16382        if (val != mSystemUiVisibility) {
16383            setSystemUiVisibility(val);
16384            return true;
16385        }
16386        return false;
16387    }
16388
16389    /** @hide */
16390    public void setDisabledSystemUiVisibility(int flags) {
16391        if (mAttachInfo != null) {
16392            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16393                mAttachInfo.mDisabledSystemUiVisibility = flags;
16394                if (mParent != null) {
16395                    mParent.recomputeViewAttributes(this);
16396                }
16397            }
16398        }
16399    }
16400
16401    /**
16402     * Creates an image that the system displays during the drag and drop
16403     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16404     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16405     * appearance as the given View. The default also positions the center of the drag shadow
16406     * directly under the touch point. If no View is provided (the constructor with no parameters
16407     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16408     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16409     * default is an invisible drag shadow.
16410     * <p>
16411     * You are not required to use the View you provide to the constructor as the basis of the
16412     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16413     * anything you want as the drag shadow.
16414     * </p>
16415     * <p>
16416     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16417     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16418     *  size and position of the drag shadow. It uses this data to construct a
16419     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16420     *  so that your application can draw the shadow image in the Canvas.
16421     * </p>
16422     *
16423     * <div class="special reference">
16424     * <h3>Developer Guides</h3>
16425     * <p>For a guide to implementing drag and drop features, read the
16426     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16427     * </div>
16428     */
16429    public static class DragShadowBuilder {
16430        private final WeakReference<View> mView;
16431
16432        /**
16433         * Constructs a shadow image builder based on a View. By default, the resulting drag
16434         * shadow will have the same appearance and dimensions as the View, with the touch point
16435         * over the center of the View.
16436         * @param view A View. Any View in scope can be used.
16437         */
16438        public DragShadowBuilder(View view) {
16439            mView = new WeakReference<View>(view);
16440        }
16441
16442        /**
16443         * Construct a shadow builder object with no associated View.  This
16444         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16445         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16446         * to supply the drag shadow's dimensions and appearance without
16447         * reference to any View object. If they are not overridden, then the result is an
16448         * invisible drag shadow.
16449         */
16450        public DragShadowBuilder() {
16451            mView = new WeakReference<View>(null);
16452        }
16453
16454        /**
16455         * Returns the View object that had been passed to the
16456         * {@link #View.DragShadowBuilder(View)}
16457         * constructor.  If that View parameter was {@code null} or if the
16458         * {@link #View.DragShadowBuilder()}
16459         * constructor was used to instantiate the builder object, this method will return
16460         * null.
16461         *
16462         * @return The View object associate with this builder object.
16463         */
16464        @SuppressWarnings({"JavadocReference"})
16465        final public View getView() {
16466            return mView.get();
16467        }
16468
16469        /**
16470         * Provides the metrics for the shadow image. These include the dimensions of
16471         * the shadow image, and the point within that shadow that should
16472         * be centered under the touch location while dragging.
16473         * <p>
16474         * The default implementation sets the dimensions of the shadow to be the
16475         * same as the dimensions of the View itself and centers the shadow under
16476         * the touch point.
16477         * </p>
16478         *
16479         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16480         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16481         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16482         * image.
16483         *
16484         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16485         * shadow image that should be underneath the touch point during the drag and drop
16486         * operation. Your application must set {@link android.graphics.Point#x} to the
16487         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16488         */
16489        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16490            final View view = mView.get();
16491            if (view != null) {
16492                shadowSize.set(view.getWidth(), view.getHeight());
16493                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16494            } else {
16495                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16496            }
16497        }
16498
16499        /**
16500         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16501         * based on the dimensions it received from the
16502         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16503         *
16504         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16505         */
16506        public void onDrawShadow(Canvas canvas) {
16507            final View view = mView.get();
16508            if (view != null) {
16509                view.draw(canvas);
16510            } else {
16511                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16512            }
16513        }
16514    }
16515
16516    /**
16517     * Starts a drag and drop operation. When your application calls this method, it passes a
16518     * {@link android.view.View.DragShadowBuilder} object to the system. The
16519     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16520     * to get metrics for the drag shadow, and then calls the object's
16521     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16522     * <p>
16523     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16524     *  drag events to all the View objects in your application that are currently visible. It does
16525     *  this either by calling the View object's drag listener (an implementation of
16526     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16527     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16528     *  Both are passed a {@link android.view.DragEvent} object that has a
16529     *  {@link android.view.DragEvent#getAction()} value of
16530     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16531     * </p>
16532     * <p>
16533     * Your application can invoke startDrag() on any attached View object. The View object does not
16534     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16535     * be related to the View the user selected for dragging.
16536     * </p>
16537     * @param data A {@link android.content.ClipData} object pointing to the data to be
16538     * transferred by the drag and drop operation.
16539     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16540     * drag shadow.
16541     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16542     * drop operation. This Object is put into every DragEvent object sent by the system during the
16543     * current drag.
16544     * <p>
16545     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16546     * to the target Views. For example, it can contain flags that differentiate between a
16547     * a copy operation and a move operation.
16548     * </p>
16549     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16550     * so the parameter should be set to 0.
16551     * @return {@code true} if the method completes successfully, or
16552     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16553     * do a drag, and so no drag operation is in progress.
16554     */
16555    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16556            Object myLocalState, int flags) {
16557        if (ViewDebug.DEBUG_DRAG) {
16558            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16559        }
16560        boolean okay = false;
16561
16562        Point shadowSize = new Point();
16563        Point shadowTouchPoint = new Point();
16564        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16565
16566        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16567                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16568            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16569        }
16570
16571        if (ViewDebug.DEBUG_DRAG) {
16572            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16573                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16574        }
16575        Surface surface = new Surface();
16576        try {
16577            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16578                    flags, shadowSize.x, shadowSize.y, surface);
16579            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16580                    + " surface=" + surface);
16581            if (token != null) {
16582                Canvas canvas = surface.lockCanvas(null);
16583                try {
16584                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16585                    shadowBuilder.onDrawShadow(canvas);
16586                } finally {
16587                    surface.unlockCanvasAndPost(canvas);
16588                }
16589
16590                final ViewRootImpl root = getViewRootImpl();
16591
16592                // Cache the local state object for delivery with DragEvents
16593                root.setLocalDragState(myLocalState);
16594
16595                // repurpose 'shadowSize' for the last touch point
16596                root.getLastTouchPoint(shadowSize);
16597
16598                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16599                        shadowSize.x, shadowSize.y,
16600                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16601                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16602
16603                // Off and running!  Release our local surface instance; the drag
16604                // shadow surface is now managed by the system process.
16605                surface.release();
16606            }
16607        } catch (Exception e) {
16608            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16609            surface.destroy();
16610        }
16611
16612        return okay;
16613    }
16614
16615    /**
16616     * Handles drag events sent by the system following a call to
16617     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16618     *<p>
16619     * When the system calls this method, it passes a
16620     * {@link android.view.DragEvent} object. A call to
16621     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16622     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16623     * operation.
16624     * @param event The {@link android.view.DragEvent} sent by the system.
16625     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16626     * in DragEvent, indicating the type of drag event represented by this object.
16627     * @return {@code true} if the method was successful, otherwise {@code false}.
16628     * <p>
16629     *  The method should return {@code true} in response to an action type of
16630     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16631     *  operation.
16632     * </p>
16633     * <p>
16634     *  The method should also return {@code true} in response to an action type of
16635     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16636     *  {@code false} if it didn't.
16637     * </p>
16638     */
16639    public boolean onDragEvent(DragEvent event) {
16640        return false;
16641    }
16642
16643    /**
16644     * Detects if this View is enabled and has a drag event listener.
16645     * If both are true, then it calls the drag event listener with the
16646     * {@link android.view.DragEvent} it received. If the drag event listener returns
16647     * {@code true}, then dispatchDragEvent() returns {@code true}.
16648     * <p>
16649     * For all other cases, the method calls the
16650     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16651     * method and returns its result.
16652     * </p>
16653     * <p>
16654     * This ensures that a drag event is always consumed, even if the View does not have a drag
16655     * event listener. However, if the View has a listener and the listener returns true, then
16656     * onDragEvent() is not called.
16657     * </p>
16658     */
16659    public boolean dispatchDragEvent(DragEvent event) {
16660        //noinspection SimplifiableIfStatement
16661        ListenerInfo li = mListenerInfo;
16662        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16663                && li.mOnDragListener.onDrag(this, event)) {
16664            return true;
16665        }
16666        return onDragEvent(event);
16667    }
16668
16669    boolean canAcceptDrag() {
16670        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16671    }
16672
16673    /**
16674     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16675     * it is ever exposed at all.
16676     * @hide
16677     */
16678    public void onCloseSystemDialogs(String reason) {
16679    }
16680
16681    /**
16682     * Given a Drawable whose bounds have been set to draw into this view,
16683     * update a Region being computed for
16684     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16685     * that any non-transparent parts of the Drawable are removed from the
16686     * given transparent region.
16687     *
16688     * @param dr The Drawable whose transparency is to be applied to the region.
16689     * @param region A Region holding the current transparency information,
16690     * where any parts of the region that are set are considered to be
16691     * transparent.  On return, this region will be modified to have the
16692     * transparency information reduced by the corresponding parts of the
16693     * Drawable that are not transparent.
16694     * {@hide}
16695     */
16696    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16697        if (DBG) {
16698            Log.i("View", "Getting transparent region for: " + this);
16699        }
16700        final Region r = dr.getTransparentRegion();
16701        final Rect db = dr.getBounds();
16702        final AttachInfo attachInfo = mAttachInfo;
16703        if (r != null && attachInfo != null) {
16704            final int w = getRight()-getLeft();
16705            final int h = getBottom()-getTop();
16706            if (db.left > 0) {
16707                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16708                r.op(0, 0, db.left, h, Region.Op.UNION);
16709            }
16710            if (db.right < w) {
16711                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16712                r.op(db.right, 0, w, h, Region.Op.UNION);
16713            }
16714            if (db.top > 0) {
16715                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16716                r.op(0, 0, w, db.top, Region.Op.UNION);
16717            }
16718            if (db.bottom < h) {
16719                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16720                r.op(0, db.bottom, w, h, Region.Op.UNION);
16721            }
16722            final int[] location = attachInfo.mTransparentLocation;
16723            getLocationInWindow(location);
16724            r.translate(location[0], location[1]);
16725            region.op(r, Region.Op.INTERSECT);
16726        } else {
16727            region.op(db, Region.Op.DIFFERENCE);
16728        }
16729    }
16730
16731    private void checkForLongClick(int delayOffset) {
16732        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16733            mHasPerformedLongPress = false;
16734
16735            if (mPendingCheckForLongPress == null) {
16736                mPendingCheckForLongPress = new CheckForLongPress();
16737            }
16738            mPendingCheckForLongPress.rememberWindowAttachCount();
16739            postDelayed(mPendingCheckForLongPress,
16740                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16741        }
16742    }
16743
16744    /**
16745     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16746     * LayoutInflater} class, which provides a full range of options for view inflation.
16747     *
16748     * @param context The Context object for your activity or application.
16749     * @param resource The resource ID to inflate
16750     * @param root A view group that will be the parent.  Used to properly inflate the
16751     * layout_* parameters.
16752     * @see LayoutInflater
16753     */
16754    public static View inflate(Context context, int resource, ViewGroup root) {
16755        LayoutInflater factory = LayoutInflater.from(context);
16756        return factory.inflate(resource, root);
16757    }
16758
16759    /**
16760     * Scroll the view with standard behavior for scrolling beyond the normal
16761     * content boundaries. Views that call this method should override
16762     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16763     * results of an over-scroll operation.
16764     *
16765     * Views can use this method to handle any touch or fling-based scrolling.
16766     *
16767     * @param deltaX Change in X in pixels
16768     * @param deltaY Change in Y in pixels
16769     * @param scrollX Current X scroll value in pixels before applying deltaX
16770     * @param scrollY Current Y scroll value in pixels before applying deltaY
16771     * @param scrollRangeX Maximum content scroll range along the X axis
16772     * @param scrollRangeY Maximum content scroll range along the Y axis
16773     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16774     *          along the X axis.
16775     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16776     *          along the Y axis.
16777     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16778     * @return true if scrolling was clamped to an over-scroll boundary along either
16779     *          axis, false otherwise.
16780     */
16781    @SuppressWarnings({"UnusedParameters"})
16782    protected boolean overScrollBy(int deltaX, int deltaY,
16783            int scrollX, int scrollY,
16784            int scrollRangeX, int scrollRangeY,
16785            int maxOverScrollX, int maxOverScrollY,
16786            boolean isTouchEvent) {
16787        final int overScrollMode = mOverScrollMode;
16788        final boolean canScrollHorizontal =
16789                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16790        final boolean canScrollVertical =
16791                computeVerticalScrollRange() > computeVerticalScrollExtent();
16792        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16793                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16794        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16795                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16796
16797        int newScrollX = scrollX + deltaX;
16798        if (!overScrollHorizontal) {
16799            maxOverScrollX = 0;
16800        }
16801
16802        int newScrollY = scrollY + deltaY;
16803        if (!overScrollVertical) {
16804            maxOverScrollY = 0;
16805        }
16806
16807        // Clamp values if at the limits and record
16808        final int left = -maxOverScrollX;
16809        final int right = maxOverScrollX + scrollRangeX;
16810        final int top = -maxOverScrollY;
16811        final int bottom = maxOverScrollY + scrollRangeY;
16812
16813        boolean clampedX = false;
16814        if (newScrollX > right) {
16815            newScrollX = right;
16816            clampedX = true;
16817        } else if (newScrollX < left) {
16818            newScrollX = left;
16819            clampedX = true;
16820        }
16821
16822        boolean clampedY = false;
16823        if (newScrollY > bottom) {
16824            newScrollY = bottom;
16825            clampedY = true;
16826        } else if (newScrollY < top) {
16827            newScrollY = top;
16828            clampedY = true;
16829        }
16830
16831        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16832
16833        return clampedX || clampedY;
16834    }
16835
16836    /**
16837     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16838     * respond to the results of an over-scroll operation.
16839     *
16840     * @param scrollX New X scroll value in pixels
16841     * @param scrollY New Y scroll value in pixels
16842     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16843     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16844     */
16845    protected void onOverScrolled(int scrollX, int scrollY,
16846            boolean clampedX, boolean clampedY) {
16847        // Intentionally empty.
16848    }
16849
16850    /**
16851     * Returns the over-scroll mode for this view. The result will be
16852     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16853     * (allow over-scrolling only if the view content is larger than the container),
16854     * or {@link #OVER_SCROLL_NEVER}.
16855     *
16856     * @return This view's over-scroll mode.
16857     */
16858    public int getOverScrollMode() {
16859        return mOverScrollMode;
16860    }
16861
16862    /**
16863     * Set the over-scroll mode for this view. Valid over-scroll modes are
16864     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16865     * (allow over-scrolling only if the view content is larger than the container),
16866     * or {@link #OVER_SCROLL_NEVER}.
16867     *
16868     * Setting the over-scroll mode of a view will have an effect only if the
16869     * view is capable of scrolling.
16870     *
16871     * @param overScrollMode The new over-scroll mode for this view.
16872     */
16873    public void setOverScrollMode(int overScrollMode) {
16874        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16875                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16876                overScrollMode != OVER_SCROLL_NEVER) {
16877            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16878        }
16879        mOverScrollMode = overScrollMode;
16880    }
16881
16882    /**
16883     * Gets a scale factor that determines the distance the view should scroll
16884     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16885     * @return The vertical scroll scale factor.
16886     * @hide
16887     */
16888    protected float getVerticalScrollFactor() {
16889        if (mVerticalScrollFactor == 0) {
16890            TypedValue outValue = new TypedValue();
16891            if (!mContext.getTheme().resolveAttribute(
16892                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16893                throw new IllegalStateException(
16894                        "Expected theme to define listPreferredItemHeight.");
16895            }
16896            mVerticalScrollFactor = outValue.getDimension(
16897                    mContext.getResources().getDisplayMetrics());
16898        }
16899        return mVerticalScrollFactor;
16900    }
16901
16902    /**
16903     * Gets a scale factor that determines the distance the view should scroll
16904     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16905     * @return The horizontal scroll scale factor.
16906     * @hide
16907     */
16908    protected float getHorizontalScrollFactor() {
16909        // TODO: Should use something else.
16910        return getVerticalScrollFactor();
16911    }
16912
16913    /**
16914     * Return the value specifying the text direction or policy that was set with
16915     * {@link #setTextDirection(int)}.
16916     *
16917     * @return the defined text direction. It can be one of:
16918     *
16919     * {@link #TEXT_DIRECTION_INHERIT},
16920     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16921     * {@link #TEXT_DIRECTION_ANY_RTL},
16922     * {@link #TEXT_DIRECTION_LTR},
16923     * {@link #TEXT_DIRECTION_RTL},
16924     * {@link #TEXT_DIRECTION_LOCALE}
16925     *
16926     * @attr ref android.R.styleable#View_textDirection
16927     *
16928     * @hide
16929     */
16930    @ViewDebug.ExportedProperty(category = "text", mapping = {
16931            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16932            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16933            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16934            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16935            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16936            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16937    })
16938    public int getRawTextDirection() {
16939        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
16940    }
16941
16942    /**
16943     * Set the text direction.
16944     *
16945     * @param textDirection the direction to set. Should be one of:
16946     *
16947     * {@link #TEXT_DIRECTION_INHERIT},
16948     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16949     * {@link #TEXT_DIRECTION_ANY_RTL},
16950     * {@link #TEXT_DIRECTION_LTR},
16951     * {@link #TEXT_DIRECTION_RTL},
16952     * {@link #TEXT_DIRECTION_LOCALE}
16953     *
16954     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
16955     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
16956     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
16957     *
16958     * @attr ref android.R.styleable#View_textDirection
16959     */
16960    public void setTextDirection(int textDirection) {
16961        if (getRawTextDirection() != textDirection) {
16962            // Reset the current text direction and the resolved one
16963            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
16964            resetResolvedTextDirection();
16965            // Set the new text direction
16966            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
16967            // Do resolution
16968            resolveTextDirection();
16969            // Notify change
16970            onRtlPropertiesChanged(getLayoutDirection());
16971            // Refresh
16972            requestLayout();
16973            invalidate(true);
16974        }
16975    }
16976
16977    /**
16978     * Return the resolved text direction.
16979     *
16980     * @return the resolved text direction. Returns one of:
16981     *
16982     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16983     * {@link #TEXT_DIRECTION_ANY_RTL},
16984     * {@link #TEXT_DIRECTION_LTR},
16985     * {@link #TEXT_DIRECTION_RTL},
16986     * {@link #TEXT_DIRECTION_LOCALE}
16987     *
16988     * @attr ref android.R.styleable#View_textDirection
16989     */
16990    @ViewDebug.ExportedProperty(category = "text", mapping = {
16991            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16992            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16993            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16994            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16995            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16996            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16997    })
16998    public int getTextDirection() {
16999        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
17000    }
17001
17002    /**
17003     * Resolve the text direction.
17004     *
17005     * @return true if resolution has been done, false otherwise.
17006     *
17007     * @hide
17008     */
17009    public boolean resolveTextDirection() {
17010        // Reset any previous text direction resolution
17011        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17012
17013        if (hasRtlSupport()) {
17014            // Set resolved text direction flag depending on text direction flag
17015            final int textDirection = getRawTextDirection();
17016            switch(textDirection) {
17017                case TEXT_DIRECTION_INHERIT:
17018                    if (!canResolveTextDirection()) {
17019                        // We cannot do the resolution if there is no parent, so use the default one
17020                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17021                        // Resolution will need to happen again later
17022                        return false;
17023                    }
17024
17025                    // Parent has not yet resolved, so we still return the default
17026                    if (!mParent.isTextDirectionResolved()) {
17027                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17028                        // Resolution will need to happen again later
17029                        return false;
17030                    }
17031
17032                    // Set current resolved direction to the same value as the parent's one
17033                    final int parentResolvedDirection = mParent.getTextDirection();
17034                    switch (parentResolvedDirection) {
17035                        case TEXT_DIRECTION_FIRST_STRONG:
17036                        case TEXT_DIRECTION_ANY_RTL:
17037                        case TEXT_DIRECTION_LTR:
17038                        case TEXT_DIRECTION_RTL:
17039                        case TEXT_DIRECTION_LOCALE:
17040                            mPrivateFlags2 |=
17041                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17042                            break;
17043                        default:
17044                            // Default resolved direction is "first strong" heuristic
17045                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17046                    }
17047                    break;
17048                case TEXT_DIRECTION_FIRST_STRONG:
17049                case TEXT_DIRECTION_ANY_RTL:
17050                case TEXT_DIRECTION_LTR:
17051                case TEXT_DIRECTION_RTL:
17052                case TEXT_DIRECTION_LOCALE:
17053                    // Resolved direction is the same as text direction
17054                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
17055                    break;
17056                default:
17057                    // Default resolved direction is "first strong" heuristic
17058                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17059            }
17060        } else {
17061            // Default resolved direction is "first strong" heuristic
17062            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17063        }
17064
17065        // Set to resolved
17066        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
17067        return true;
17068    }
17069
17070    /**
17071     * Check if text direction resolution can be done.
17072     *
17073     * @return true if text direction resolution can be done otherwise return false.
17074     *
17075     * @hide
17076     */
17077    public boolean canResolveTextDirection() {
17078        switch (getRawTextDirection()) {
17079            case TEXT_DIRECTION_INHERIT:
17080                return (mParent != null) && mParent.canResolveTextDirection();
17081            default:
17082                return true;
17083        }
17084    }
17085
17086    /**
17087     * Reset resolved text direction. Text direction will be resolved during a call to
17088     * {@link #onMeasure(int, int)}.
17089     *
17090     * @hide
17091     */
17092    public void resetResolvedTextDirection() {
17093        // Reset any previous text direction resolution
17094        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17095        // Set to default value
17096        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17097    }
17098
17099    /**
17100     * @return true if text direction is inherited.
17101     *
17102     * @hide
17103     */
17104    public boolean isTextDirectionInherited() {
17105        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17106    }
17107
17108    /**
17109     * @return true if text direction is resolved.
17110     *
17111     * @hide
17112     */
17113    public boolean isTextDirectionResolved() {
17114        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17115    }
17116
17117    /**
17118     * Return the value specifying the text alignment or policy that was set with
17119     * {@link #setTextAlignment(int)}.
17120     *
17121     * @return the defined text alignment. It can be one of:
17122     *
17123     * {@link #TEXT_ALIGNMENT_INHERIT},
17124     * {@link #TEXT_ALIGNMENT_GRAVITY},
17125     * {@link #TEXT_ALIGNMENT_CENTER},
17126     * {@link #TEXT_ALIGNMENT_TEXT_START},
17127     * {@link #TEXT_ALIGNMENT_TEXT_END},
17128     * {@link #TEXT_ALIGNMENT_VIEW_START},
17129     * {@link #TEXT_ALIGNMENT_VIEW_END}
17130     *
17131     * @attr ref android.R.styleable#View_textAlignment
17132     *
17133     * @hide
17134     */
17135    @ViewDebug.ExportedProperty(category = "text", mapping = {
17136            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17137            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17138            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17139            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17140            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17141            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17142            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17143    })
17144    public int getRawTextAlignment() {
17145        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17146    }
17147
17148    /**
17149     * Set the text alignment.
17150     *
17151     * @param textAlignment The text alignment to set. Should be one of
17152     *
17153     * {@link #TEXT_ALIGNMENT_INHERIT},
17154     * {@link #TEXT_ALIGNMENT_GRAVITY},
17155     * {@link #TEXT_ALIGNMENT_CENTER},
17156     * {@link #TEXT_ALIGNMENT_TEXT_START},
17157     * {@link #TEXT_ALIGNMENT_TEXT_END},
17158     * {@link #TEXT_ALIGNMENT_VIEW_START},
17159     * {@link #TEXT_ALIGNMENT_VIEW_END}
17160     *
17161     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17162     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17163     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17164     *
17165     * @attr ref android.R.styleable#View_textAlignment
17166     */
17167    public void setTextAlignment(int textAlignment) {
17168        if (textAlignment != getRawTextAlignment()) {
17169            // Reset the current and resolved text alignment
17170            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17171            resetResolvedTextAlignment();
17172            // Set the new text alignment
17173            mPrivateFlags2 |=
17174                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17175            // Do resolution
17176            resolveTextAlignment();
17177            // Notify change
17178            onRtlPropertiesChanged(getLayoutDirection());
17179            // Refresh
17180            requestLayout();
17181            invalidate(true);
17182        }
17183    }
17184
17185    /**
17186     * Return the resolved text alignment.
17187     *
17188     * @return the resolved text alignment. Returns one of:
17189     *
17190     * {@link #TEXT_ALIGNMENT_GRAVITY},
17191     * {@link #TEXT_ALIGNMENT_CENTER},
17192     * {@link #TEXT_ALIGNMENT_TEXT_START},
17193     * {@link #TEXT_ALIGNMENT_TEXT_END},
17194     * {@link #TEXT_ALIGNMENT_VIEW_START},
17195     * {@link #TEXT_ALIGNMENT_VIEW_END}
17196     *
17197     * @attr ref android.R.styleable#View_textAlignment
17198     */
17199    @ViewDebug.ExportedProperty(category = "text", mapping = {
17200            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17201            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17202            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17203            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17204            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17205            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17206            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17207    })
17208    public int getTextAlignment() {
17209        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17210                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17211    }
17212
17213    /**
17214     * Resolve the text alignment.
17215     *
17216     * @return true if resolution has been done, false otherwise.
17217     *
17218     * @hide
17219     */
17220    public boolean resolveTextAlignment() {
17221        // Reset any previous text alignment resolution
17222        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17223
17224        if (hasRtlSupport()) {
17225            // Set resolved text alignment flag depending on text alignment flag
17226            final int textAlignment = getRawTextAlignment();
17227            switch (textAlignment) {
17228                case TEXT_ALIGNMENT_INHERIT:
17229                    // Check if we can resolve the text alignment
17230                    if (!canResolveTextAlignment()) {
17231                        // We cannot do the resolution if there is no parent so use the default
17232                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17233                        // Resolution will need to happen again later
17234                        return false;
17235                    }
17236
17237                    // Parent has not yet resolved, so we still return the default
17238                    if (!mParent.isTextAlignmentResolved()) {
17239                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17240                        // Resolution will need to happen again later
17241                        return false;
17242                    }
17243
17244                    final int parentResolvedTextAlignment = mParent.getTextAlignment();
17245                    switch (parentResolvedTextAlignment) {
17246                        case TEXT_ALIGNMENT_GRAVITY:
17247                        case TEXT_ALIGNMENT_TEXT_START:
17248                        case TEXT_ALIGNMENT_TEXT_END:
17249                        case TEXT_ALIGNMENT_CENTER:
17250                        case TEXT_ALIGNMENT_VIEW_START:
17251                        case TEXT_ALIGNMENT_VIEW_END:
17252                            // Resolved text alignment is the same as the parent resolved
17253                            // text alignment
17254                            mPrivateFlags2 |=
17255                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17256                            break;
17257                        default:
17258                            // Use default resolved text alignment
17259                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17260                    }
17261                    break;
17262                case TEXT_ALIGNMENT_GRAVITY:
17263                case TEXT_ALIGNMENT_TEXT_START:
17264                case TEXT_ALIGNMENT_TEXT_END:
17265                case TEXT_ALIGNMENT_CENTER:
17266                case TEXT_ALIGNMENT_VIEW_START:
17267                case TEXT_ALIGNMENT_VIEW_END:
17268                    // Resolved text alignment is the same as text alignment
17269                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17270                    break;
17271                default:
17272                    // Use default resolved text alignment
17273                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17274            }
17275        } else {
17276            // Use default resolved text alignment
17277            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17278        }
17279
17280        // Set the resolved
17281        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17282        return true;
17283    }
17284
17285    /**
17286     * Check if text alignment resolution can be done.
17287     *
17288     * @return true if text alignment resolution can be done otherwise return false.
17289     *
17290     * @hide
17291     */
17292    public boolean canResolveTextAlignment() {
17293        switch (getRawTextAlignment()) {
17294            case TEXT_DIRECTION_INHERIT:
17295                return (mParent != null) && mParent.canResolveTextAlignment();
17296            default:
17297                return true;
17298        }
17299    }
17300
17301    /**
17302     * Reset resolved text alignment. Text alignment will be resolved during a call to
17303     * {@link #onMeasure(int, int)}.
17304     *
17305     * @hide
17306     */
17307    public void resetResolvedTextAlignment() {
17308        // Reset any previous text alignment resolution
17309        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17310        // Set to default
17311        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17312    }
17313
17314    /**
17315     * @return true if text alignment is inherited.
17316     *
17317     * @hide
17318     */
17319    public boolean isTextAlignmentInherited() {
17320        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17321    }
17322
17323    /**
17324     * @return true if text alignment is resolved.
17325     *
17326     * @hide
17327     */
17328    public boolean isTextAlignmentResolved() {
17329        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17330    }
17331
17332    /**
17333     * Generate a value suitable for use in {@link #setId(int)}.
17334     * This value will not collide with ID values generated at build time by aapt for R.id.
17335     *
17336     * @return a generated ID value
17337     */
17338    public static int generateViewId() {
17339        for (;;) {
17340            final int result = sNextGeneratedId.get();
17341            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17342            int newValue = result + 1;
17343            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17344            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17345                return result;
17346            }
17347        }
17348    }
17349
17350    //
17351    // Properties
17352    //
17353    /**
17354     * A Property wrapper around the <code>alpha</code> functionality handled by the
17355     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17356     */
17357    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17358        @Override
17359        public void setValue(View object, float value) {
17360            object.setAlpha(value);
17361        }
17362
17363        @Override
17364        public Float get(View object) {
17365            return object.getAlpha();
17366        }
17367    };
17368
17369    /**
17370     * A Property wrapper around the <code>translationX</code> functionality handled by the
17371     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17372     */
17373    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17374        @Override
17375        public void setValue(View object, float value) {
17376            object.setTranslationX(value);
17377        }
17378
17379                @Override
17380        public Float get(View object) {
17381            return object.getTranslationX();
17382        }
17383    };
17384
17385    /**
17386     * A Property wrapper around the <code>translationY</code> functionality handled by the
17387     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17388     */
17389    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17390        @Override
17391        public void setValue(View object, float value) {
17392            object.setTranslationY(value);
17393        }
17394
17395        @Override
17396        public Float get(View object) {
17397            return object.getTranslationY();
17398        }
17399    };
17400
17401    /**
17402     * A Property wrapper around the <code>x</code> functionality handled by the
17403     * {@link View#setX(float)} and {@link View#getX()} methods.
17404     */
17405    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17406        @Override
17407        public void setValue(View object, float value) {
17408            object.setX(value);
17409        }
17410
17411        @Override
17412        public Float get(View object) {
17413            return object.getX();
17414        }
17415    };
17416
17417    /**
17418     * A Property wrapper around the <code>y</code> functionality handled by the
17419     * {@link View#setY(float)} and {@link View#getY()} methods.
17420     */
17421    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17422        @Override
17423        public void setValue(View object, float value) {
17424            object.setY(value);
17425        }
17426
17427        @Override
17428        public Float get(View object) {
17429            return object.getY();
17430        }
17431    };
17432
17433    /**
17434     * A Property wrapper around the <code>rotation</code> functionality handled by the
17435     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17436     */
17437    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17438        @Override
17439        public void setValue(View object, float value) {
17440            object.setRotation(value);
17441        }
17442
17443        @Override
17444        public Float get(View object) {
17445            return object.getRotation();
17446        }
17447    };
17448
17449    /**
17450     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17451     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17452     */
17453    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17454        @Override
17455        public void setValue(View object, float value) {
17456            object.setRotationX(value);
17457        }
17458
17459        @Override
17460        public Float get(View object) {
17461            return object.getRotationX();
17462        }
17463    };
17464
17465    /**
17466     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17467     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17468     */
17469    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17470        @Override
17471        public void setValue(View object, float value) {
17472            object.setRotationY(value);
17473        }
17474
17475        @Override
17476        public Float get(View object) {
17477            return object.getRotationY();
17478        }
17479    };
17480
17481    /**
17482     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17483     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17484     */
17485    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17486        @Override
17487        public void setValue(View object, float value) {
17488            object.setScaleX(value);
17489        }
17490
17491        @Override
17492        public Float get(View object) {
17493            return object.getScaleX();
17494        }
17495    };
17496
17497    /**
17498     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17499     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17500     */
17501    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17502        @Override
17503        public void setValue(View object, float value) {
17504            object.setScaleY(value);
17505        }
17506
17507        @Override
17508        public Float get(View object) {
17509            return object.getScaleY();
17510        }
17511    };
17512
17513    /**
17514     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17515     * Each MeasureSpec represents a requirement for either the width or the height.
17516     * A MeasureSpec is comprised of a size and a mode. There are three possible
17517     * modes:
17518     * <dl>
17519     * <dt>UNSPECIFIED</dt>
17520     * <dd>
17521     * The parent has not imposed any constraint on the child. It can be whatever size
17522     * it wants.
17523     * </dd>
17524     *
17525     * <dt>EXACTLY</dt>
17526     * <dd>
17527     * The parent has determined an exact size for the child. The child is going to be
17528     * given those bounds regardless of how big it wants to be.
17529     * </dd>
17530     *
17531     * <dt>AT_MOST</dt>
17532     * <dd>
17533     * The child can be as large as it wants up to the specified size.
17534     * </dd>
17535     * </dl>
17536     *
17537     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17538     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17539     */
17540    public static class MeasureSpec {
17541        private static final int MODE_SHIFT = 30;
17542        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17543
17544        /**
17545         * Measure specification mode: The parent has not imposed any constraint
17546         * on the child. It can be whatever size it wants.
17547         */
17548        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17549
17550        /**
17551         * Measure specification mode: The parent has determined an exact size
17552         * for the child. The child is going to be given those bounds regardless
17553         * of how big it wants to be.
17554         */
17555        public static final int EXACTLY     = 1 << MODE_SHIFT;
17556
17557        /**
17558         * Measure specification mode: The child can be as large as it wants up
17559         * to the specified size.
17560         */
17561        public static final int AT_MOST     = 2 << MODE_SHIFT;
17562
17563        /**
17564         * Creates a measure specification based on the supplied size and mode.
17565         *
17566         * The mode must always be one of the following:
17567         * <ul>
17568         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17569         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17570         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17571         * </ul>
17572         *
17573         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17574         * implementation was such that the order of arguments did not matter
17575         * and overflow in either value could impact the resulting MeasureSpec.
17576         * {@link android.widget.RelativeLayout} was affected by this bug.
17577         * Apps targeting API levels greater than 17 will get the fixed, more strict
17578         * behavior.</p>
17579         *
17580         * @param size the size of the measure specification
17581         * @param mode the mode of the measure specification
17582         * @return the measure specification based on size and mode
17583         */
17584        public static int makeMeasureSpec(int size, int mode) {
17585            if (sUseBrokenMakeMeasureSpec) {
17586                return size + mode;
17587            } else {
17588                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17589            }
17590        }
17591
17592        /**
17593         * Extracts the mode from the supplied measure specification.
17594         *
17595         * @param measureSpec the measure specification to extract the mode from
17596         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17597         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17598         *         {@link android.view.View.MeasureSpec#EXACTLY}
17599         */
17600        public static int getMode(int measureSpec) {
17601            return (measureSpec & MODE_MASK);
17602        }
17603
17604        /**
17605         * Extracts the size from the supplied measure specification.
17606         *
17607         * @param measureSpec the measure specification to extract the size from
17608         * @return the size in pixels defined in the supplied measure specification
17609         */
17610        public static int getSize(int measureSpec) {
17611            return (measureSpec & ~MODE_MASK);
17612        }
17613
17614        static int adjust(int measureSpec, int delta) {
17615            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17616        }
17617
17618        /**
17619         * Returns a String representation of the specified measure
17620         * specification.
17621         *
17622         * @param measureSpec the measure specification to convert to a String
17623         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17624         */
17625        public static String toString(int measureSpec) {
17626            int mode = getMode(measureSpec);
17627            int size = getSize(measureSpec);
17628
17629            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17630
17631            if (mode == UNSPECIFIED)
17632                sb.append("UNSPECIFIED ");
17633            else if (mode == EXACTLY)
17634                sb.append("EXACTLY ");
17635            else if (mode == AT_MOST)
17636                sb.append("AT_MOST ");
17637            else
17638                sb.append(mode).append(" ");
17639
17640            sb.append(size);
17641            return sb.toString();
17642        }
17643    }
17644
17645    class CheckForLongPress implements Runnable {
17646
17647        private int mOriginalWindowAttachCount;
17648
17649        public void run() {
17650            if (isPressed() && (mParent != null)
17651                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17652                if (performLongClick()) {
17653                    mHasPerformedLongPress = true;
17654                }
17655            }
17656        }
17657
17658        public void rememberWindowAttachCount() {
17659            mOriginalWindowAttachCount = mWindowAttachCount;
17660        }
17661    }
17662
17663    private final class CheckForTap implements Runnable {
17664        public void run() {
17665            mPrivateFlags &= ~PFLAG_PREPRESSED;
17666            setPressed(true);
17667            checkForLongClick(ViewConfiguration.getTapTimeout());
17668        }
17669    }
17670
17671    private final class PerformClick implements Runnable {
17672        public void run() {
17673            performClick();
17674        }
17675    }
17676
17677    /** @hide */
17678    public void hackTurnOffWindowResizeAnim(boolean off) {
17679        mAttachInfo.mTurnOffWindowResizeAnim = off;
17680    }
17681
17682    /**
17683     * This method returns a ViewPropertyAnimator object, which can be used to animate
17684     * specific properties on this View.
17685     *
17686     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17687     */
17688    public ViewPropertyAnimator animate() {
17689        if (mAnimator == null) {
17690            mAnimator = new ViewPropertyAnimator(this);
17691        }
17692        return mAnimator;
17693    }
17694
17695    /**
17696     * Interface definition for a callback to be invoked when a hardware key event is
17697     * dispatched to this view. The callback will be invoked before the key event is
17698     * given to the view. This is only useful for hardware keyboards; a software input
17699     * method has no obligation to trigger this listener.
17700     */
17701    public interface OnKeyListener {
17702        /**
17703         * Called when a hardware key is dispatched to a view. This allows listeners to
17704         * get a chance to respond before the target view.
17705         * <p>Key presses in software keyboards will generally NOT trigger this method,
17706         * although some may elect to do so in some situations. Do not assume a
17707         * software input method has to be key-based; even if it is, it may use key presses
17708         * in a different way than you expect, so there is no way to reliably catch soft
17709         * input key presses.
17710         *
17711         * @param v The view the key has been dispatched to.
17712         * @param keyCode The code for the physical key that was pressed
17713         * @param event The KeyEvent object containing full information about
17714         *        the event.
17715         * @return True if the listener has consumed the event, false otherwise.
17716         */
17717        boolean onKey(View v, int keyCode, KeyEvent event);
17718    }
17719
17720    /**
17721     * Interface definition for a callback to be invoked when a touch event is
17722     * dispatched to this view. The callback will be invoked before the touch
17723     * event is given to the view.
17724     */
17725    public interface OnTouchListener {
17726        /**
17727         * Called when a touch event is dispatched to a view. This allows listeners to
17728         * get a chance to respond before the target view.
17729         *
17730         * @param v The view the touch event has been dispatched to.
17731         * @param event The MotionEvent object containing full information about
17732         *        the event.
17733         * @return True if the listener has consumed the event, false otherwise.
17734         */
17735        boolean onTouch(View v, MotionEvent event);
17736    }
17737
17738    /**
17739     * Interface definition for a callback to be invoked when a hover event is
17740     * dispatched to this view. The callback will be invoked before the hover
17741     * event is given to the view.
17742     */
17743    public interface OnHoverListener {
17744        /**
17745         * Called when a hover event is dispatched to a view. This allows listeners to
17746         * get a chance to respond before the target view.
17747         *
17748         * @param v The view the hover event has been dispatched to.
17749         * @param event The MotionEvent object containing full information about
17750         *        the event.
17751         * @return True if the listener has consumed the event, false otherwise.
17752         */
17753        boolean onHover(View v, MotionEvent event);
17754    }
17755
17756    /**
17757     * Interface definition for a callback to be invoked when a generic motion event is
17758     * dispatched to this view. The callback will be invoked before the generic motion
17759     * event is given to the view.
17760     */
17761    public interface OnGenericMotionListener {
17762        /**
17763         * Called when a generic motion event is dispatched to a view. This allows listeners to
17764         * get a chance to respond before the target view.
17765         *
17766         * @param v The view the generic motion event has been dispatched to.
17767         * @param event The MotionEvent object containing full information about
17768         *        the event.
17769         * @return True if the listener has consumed the event, false otherwise.
17770         */
17771        boolean onGenericMotion(View v, MotionEvent event);
17772    }
17773
17774    /**
17775     * Interface definition for a callback to be invoked when a view has been clicked and held.
17776     */
17777    public interface OnLongClickListener {
17778        /**
17779         * Called when a view has been clicked and held.
17780         *
17781         * @param v The view that was clicked and held.
17782         *
17783         * @return true if the callback consumed the long click, false otherwise.
17784         */
17785        boolean onLongClick(View v);
17786    }
17787
17788    /**
17789     * Interface definition for a callback to be invoked when a drag is being dispatched
17790     * to this view.  The callback will be invoked before the hosting view's own
17791     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17792     * onDrag(event) behavior, it should return 'false' from this callback.
17793     *
17794     * <div class="special reference">
17795     * <h3>Developer Guides</h3>
17796     * <p>For a guide to implementing drag and drop features, read the
17797     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17798     * </div>
17799     */
17800    public interface OnDragListener {
17801        /**
17802         * Called when a drag event is dispatched to a view. This allows listeners
17803         * to get a chance to override base View behavior.
17804         *
17805         * @param v The View that received the drag event.
17806         * @param event The {@link android.view.DragEvent} object for the drag event.
17807         * @return {@code true} if the drag event was handled successfully, or {@code false}
17808         * if the drag event was not handled. Note that {@code false} will trigger the View
17809         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17810         */
17811        boolean onDrag(View v, DragEvent event);
17812    }
17813
17814    /**
17815     * Interface definition for a callback to be invoked when the focus state of
17816     * a view changed.
17817     */
17818    public interface OnFocusChangeListener {
17819        /**
17820         * Called when the focus state of a view has changed.
17821         *
17822         * @param v The view whose state has changed.
17823         * @param hasFocus The new focus state of v.
17824         */
17825        void onFocusChange(View v, boolean hasFocus);
17826    }
17827
17828    /**
17829     * Interface definition for a callback to be invoked when a view is clicked.
17830     */
17831    public interface OnClickListener {
17832        /**
17833         * Called when a view has been clicked.
17834         *
17835         * @param v The view that was clicked.
17836         */
17837        void onClick(View v);
17838    }
17839
17840    /**
17841     * Interface definition for a callback to be invoked when the context menu
17842     * for this view is being built.
17843     */
17844    public interface OnCreateContextMenuListener {
17845        /**
17846         * Called when the context menu for this view is being built. It is not
17847         * safe to hold onto the menu after this method returns.
17848         *
17849         * @param menu The context menu that is being built
17850         * @param v The view for which the context menu is being built
17851         * @param menuInfo Extra information about the item for which the
17852         *            context menu should be shown. This information will vary
17853         *            depending on the class of v.
17854         */
17855        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17856    }
17857
17858    /**
17859     * Interface definition for a callback to be invoked when the status bar changes
17860     * visibility.  This reports <strong>global</strong> changes to the system UI
17861     * state, not what the application is requesting.
17862     *
17863     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17864     */
17865    public interface OnSystemUiVisibilityChangeListener {
17866        /**
17867         * Called when the status bar changes visibility because of a call to
17868         * {@link View#setSystemUiVisibility(int)}.
17869         *
17870         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17871         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17872         * This tells you the <strong>global</strong> state of these UI visibility
17873         * flags, not what your app is currently applying.
17874         */
17875        public void onSystemUiVisibilityChange(int visibility);
17876    }
17877
17878    /**
17879     * Interface definition for a callback to be invoked when this view is attached
17880     * or detached from its window.
17881     */
17882    public interface OnAttachStateChangeListener {
17883        /**
17884         * Called when the view is attached to a window.
17885         * @param v The view that was attached
17886         */
17887        public void onViewAttachedToWindow(View v);
17888        /**
17889         * Called when the view is detached from a window.
17890         * @param v The view that was detached
17891         */
17892        public void onViewDetachedFromWindow(View v);
17893    }
17894
17895    private final class UnsetPressedState implements Runnable {
17896        public void run() {
17897            setPressed(false);
17898        }
17899    }
17900
17901    /**
17902     * Base class for derived classes that want to save and restore their own
17903     * state in {@link android.view.View#onSaveInstanceState()}.
17904     */
17905    public static class BaseSavedState extends AbsSavedState {
17906        /**
17907         * Constructor used when reading from a parcel. Reads the state of the superclass.
17908         *
17909         * @param source
17910         */
17911        public BaseSavedState(Parcel source) {
17912            super(source);
17913        }
17914
17915        /**
17916         * Constructor called by derived classes when creating their SavedState objects
17917         *
17918         * @param superState The state of the superclass of this view
17919         */
17920        public BaseSavedState(Parcelable superState) {
17921            super(superState);
17922        }
17923
17924        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17925                new Parcelable.Creator<BaseSavedState>() {
17926            public BaseSavedState createFromParcel(Parcel in) {
17927                return new BaseSavedState(in);
17928            }
17929
17930            public BaseSavedState[] newArray(int size) {
17931                return new BaseSavedState[size];
17932            }
17933        };
17934    }
17935
17936    /**
17937     * A set of information given to a view when it is attached to its parent
17938     * window.
17939     */
17940    static class AttachInfo {
17941        interface Callbacks {
17942            void playSoundEffect(int effectId);
17943            boolean performHapticFeedback(int effectId, boolean always);
17944        }
17945
17946        /**
17947         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17948         * to a Handler. This class contains the target (View) to invalidate and
17949         * the coordinates of the dirty rectangle.
17950         *
17951         * For performance purposes, this class also implements a pool of up to
17952         * POOL_LIMIT objects that get reused. This reduces memory allocations
17953         * whenever possible.
17954         */
17955        static class InvalidateInfo {
17956            private static final int POOL_LIMIT = 10;
17957
17958            private static final SynchronizedPool<InvalidateInfo> sPool =
17959                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
17960
17961            View target;
17962
17963            int left;
17964            int top;
17965            int right;
17966            int bottom;
17967
17968            public static InvalidateInfo obtain() {
17969                InvalidateInfo instance = sPool.acquire();
17970                return (instance != null) ? instance : new InvalidateInfo();
17971            }
17972
17973            public void recycle() {
17974                target = null;
17975                sPool.release(this);
17976            }
17977        }
17978
17979        final IWindowSession mSession;
17980
17981        final IWindow mWindow;
17982
17983        final IBinder mWindowToken;
17984
17985        final Display mDisplay;
17986
17987        final Callbacks mRootCallbacks;
17988
17989        HardwareCanvas mHardwareCanvas;
17990
17991        IWindowId mIWindowId;
17992        WindowId mWindowId;
17993
17994        /**
17995         * The top view of the hierarchy.
17996         */
17997        View mRootView;
17998
17999        IBinder mPanelParentWindowToken;
18000        Surface mSurface;
18001
18002        boolean mHardwareAccelerated;
18003        boolean mHardwareAccelerationRequested;
18004        HardwareRenderer mHardwareRenderer;
18005
18006        boolean mScreenOn;
18007
18008        /**
18009         * Scale factor used by the compatibility mode
18010         */
18011        float mApplicationScale;
18012
18013        /**
18014         * Indicates whether the application is in compatibility mode
18015         */
18016        boolean mScalingRequired;
18017
18018        /**
18019         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
18020         */
18021        boolean mTurnOffWindowResizeAnim;
18022
18023        /**
18024         * Left position of this view's window
18025         */
18026        int mWindowLeft;
18027
18028        /**
18029         * Top position of this view's window
18030         */
18031        int mWindowTop;
18032
18033        /**
18034         * Indicates whether views need to use 32-bit drawing caches
18035         */
18036        boolean mUse32BitDrawingCache;
18037
18038        /**
18039         * For windows that are full-screen but using insets to layout inside
18040         * of the screen areas, these are the current insets to appear inside
18041         * the overscan area of the display.
18042         */
18043        final Rect mOverscanInsets = new Rect();
18044
18045        /**
18046         * For windows that are full-screen but using insets to layout inside
18047         * of the screen decorations, these are the current insets for the
18048         * content of the window.
18049         */
18050        final Rect mContentInsets = new Rect();
18051
18052        /**
18053         * For windows that are full-screen but using insets to layout inside
18054         * of the screen decorations, these are the current insets for the
18055         * actual visible parts of the window.
18056         */
18057        final Rect mVisibleInsets = new Rect();
18058
18059        /**
18060         * The internal insets given by this window.  This value is
18061         * supplied by the client (through
18062         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
18063         * be given to the window manager when changed to be used in laying
18064         * out windows behind it.
18065         */
18066        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
18067                = new ViewTreeObserver.InternalInsetsInfo();
18068
18069        /**
18070         * All views in the window's hierarchy that serve as scroll containers,
18071         * used to determine if the window can be resized or must be panned
18072         * to adjust for a soft input area.
18073         */
18074        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18075
18076        final KeyEvent.DispatcherState mKeyDispatchState
18077                = new KeyEvent.DispatcherState();
18078
18079        /**
18080         * Indicates whether the view's window currently has the focus.
18081         */
18082        boolean mHasWindowFocus;
18083
18084        /**
18085         * The current visibility of the window.
18086         */
18087        int mWindowVisibility;
18088
18089        /**
18090         * Indicates the time at which drawing started to occur.
18091         */
18092        long mDrawingTime;
18093
18094        /**
18095         * Indicates whether or not ignoring the DIRTY_MASK flags.
18096         */
18097        boolean mIgnoreDirtyState;
18098
18099        /**
18100         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18101         * to avoid clearing that flag prematurely.
18102         */
18103        boolean mSetIgnoreDirtyState = false;
18104
18105        /**
18106         * Indicates whether the view's window is currently in touch mode.
18107         */
18108        boolean mInTouchMode;
18109
18110        /**
18111         * Indicates that ViewAncestor should trigger a global layout change
18112         * the next time it performs a traversal
18113         */
18114        boolean mRecomputeGlobalAttributes;
18115
18116        /**
18117         * Always report new attributes at next traversal.
18118         */
18119        boolean mForceReportNewAttributes;
18120
18121        /**
18122         * Set during a traveral if any views want to keep the screen on.
18123         */
18124        boolean mKeepScreenOn;
18125
18126        /**
18127         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18128         */
18129        int mSystemUiVisibility;
18130
18131        /**
18132         * Hack to force certain system UI visibility flags to be cleared.
18133         */
18134        int mDisabledSystemUiVisibility;
18135
18136        /**
18137         * Last global system UI visibility reported by the window manager.
18138         */
18139        int mGlobalSystemUiVisibility;
18140
18141        /**
18142         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18143         * attached.
18144         */
18145        boolean mHasSystemUiListeners;
18146
18147        /**
18148         * Set if the window has requested to extend into the overscan region
18149         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18150         */
18151        boolean mOverscanRequested;
18152
18153        /**
18154         * Set if the visibility of any views has changed.
18155         */
18156        boolean mViewVisibilityChanged;
18157
18158        /**
18159         * Set to true if a view has been scrolled.
18160         */
18161        boolean mViewScrollChanged;
18162
18163        /**
18164         * Global to the view hierarchy used as a temporary for dealing with
18165         * x/y points in the transparent region computations.
18166         */
18167        final int[] mTransparentLocation = new int[2];
18168
18169        /**
18170         * Global to the view hierarchy used as a temporary for dealing with
18171         * x/y points in the ViewGroup.invalidateChild implementation.
18172         */
18173        final int[] mInvalidateChildLocation = new int[2];
18174
18175
18176        /**
18177         * Global to the view hierarchy used as a temporary for dealing with
18178         * x/y location when view is transformed.
18179         */
18180        final float[] mTmpTransformLocation = new float[2];
18181
18182        /**
18183         * The view tree observer used to dispatch global events like
18184         * layout, pre-draw, touch mode change, etc.
18185         */
18186        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18187
18188        /**
18189         * A Canvas used by the view hierarchy to perform bitmap caching.
18190         */
18191        Canvas mCanvas;
18192
18193        /**
18194         * The view root impl.
18195         */
18196        final ViewRootImpl mViewRootImpl;
18197
18198        /**
18199         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18200         * handler can be used to pump events in the UI events queue.
18201         */
18202        final Handler mHandler;
18203
18204        /**
18205         * Temporary for use in computing invalidate rectangles while
18206         * calling up the hierarchy.
18207         */
18208        final Rect mTmpInvalRect = new Rect();
18209
18210        /**
18211         * Temporary for use in computing hit areas with transformed views
18212         */
18213        final RectF mTmpTransformRect = new RectF();
18214
18215        /**
18216         * Temporary for use in transforming invalidation rect
18217         */
18218        final Matrix mTmpMatrix = new Matrix();
18219
18220        /**
18221         * Temporary for use in transforming invalidation rect
18222         */
18223        final Transformation mTmpTransformation = new Transformation();
18224
18225        /**
18226         * Temporary list for use in collecting focusable descendents of a view.
18227         */
18228        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18229
18230        /**
18231         * The id of the window for accessibility purposes.
18232         */
18233        int mAccessibilityWindowId = View.NO_ID;
18234
18235        /**
18236         * Flags related to accessibility processing.
18237         *
18238         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18239         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18240         */
18241        int mAccessibilityFetchFlags;
18242
18243        /**
18244         * The drawable for highlighting accessibility focus.
18245         */
18246        Drawable mAccessibilityFocusDrawable;
18247
18248        /**
18249         * Show where the margins, bounds and layout bounds are for each view.
18250         */
18251        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18252
18253        /**
18254         * Point used to compute visible regions.
18255         */
18256        final Point mPoint = new Point();
18257
18258        /**
18259         * Used to track which View originated a requestLayout() call, used when
18260         * requestLayout() is called during layout.
18261         */
18262        View mViewRequestingLayout;
18263
18264        /**
18265         * Creates a new set of attachment information with the specified
18266         * events handler and thread.
18267         *
18268         * @param handler the events handler the view must use
18269         */
18270        AttachInfo(IWindowSession session, IWindow window, Display display,
18271                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18272            mSession = session;
18273            mWindow = window;
18274            mWindowToken = window.asBinder();
18275            mDisplay = display;
18276            mViewRootImpl = viewRootImpl;
18277            mHandler = handler;
18278            mRootCallbacks = effectPlayer;
18279        }
18280    }
18281
18282    /**
18283     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18284     * is supported. This avoids keeping too many unused fields in most
18285     * instances of View.</p>
18286     */
18287    private static class ScrollabilityCache implements Runnable {
18288
18289        /**
18290         * Scrollbars are not visible
18291         */
18292        public static final int OFF = 0;
18293
18294        /**
18295         * Scrollbars are visible
18296         */
18297        public static final int ON = 1;
18298
18299        /**
18300         * Scrollbars are fading away
18301         */
18302        public static final int FADING = 2;
18303
18304        public boolean fadeScrollBars;
18305
18306        public int fadingEdgeLength;
18307        public int scrollBarDefaultDelayBeforeFade;
18308        public int scrollBarFadeDuration;
18309
18310        public int scrollBarSize;
18311        public ScrollBarDrawable scrollBar;
18312        public float[] interpolatorValues;
18313        public View host;
18314
18315        public final Paint paint;
18316        public final Matrix matrix;
18317        public Shader shader;
18318
18319        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18320
18321        private static final float[] OPAQUE = { 255 };
18322        private static final float[] TRANSPARENT = { 0.0f };
18323
18324        /**
18325         * When fading should start. This time moves into the future every time
18326         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18327         */
18328        public long fadeStartTime;
18329
18330
18331        /**
18332         * The current state of the scrollbars: ON, OFF, or FADING
18333         */
18334        public int state = OFF;
18335
18336        private int mLastColor;
18337
18338        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18339            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18340            scrollBarSize = configuration.getScaledScrollBarSize();
18341            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18342            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18343
18344            paint = new Paint();
18345            matrix = new Matrix();
18346            // use use a height of 1, and then wack the matrix each time we
18347            // actually use it.
18348            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18349            paint.setShader(shader);
18350            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18351
18352            this.host = host;
18353        }
18354
18355        public void setFadeColor(int color) {
18356            if (color != mLastColor) {
18357                mLastColor = color;
18358
18359                if (color != 0) {
18360                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18361                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18362                    paint.setShader(shader);
18363                    // Restore the default transfer mode (src_over)
18364                    paint.setXfermode(null);
18365                } else {
18366                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18367                    paint.setShader(shader);
18368                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18369                }
18370            }
18371        }
18372
18373        public void run() {
18374            long now = AnimationUtils.currentAnimationTimeMillis();
18375            if (now >= fadeStartTime) {
18376
18377                // the animation fades the scrollbars out by changing
18378                // the opacity (alpha) from fully opaque to fully
18379                // transparent
18380                int nextFrame = (int) now;
18381                int framesCount = 0;
18382
18383                Interpolator interpolator = scrollBarInterpolator;
18384
18385                // Start opaque
18386                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18387
18388                // End transparent
18389                nextFrame += scrollBarFadeDuration;
18390                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18391
18392                state = FADING;
18393
18394                // Kick off the fade animation
18395                host.invalidate(true);
18396            }
18397        }
18398    }
18399
18400    /**
18401     * Resuable callback for sending
18402     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18403     */
18404    private class SendViewScrolledAccessibilityEvent implements Runnable {
18405        public volatile boolean mIsPending;
18406
18407        public void run() {
18408            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18409            mIsPending = false;
18410        }
18411    }
18412
18413    /**
18414     * <p>
18415     * This class represents a delegate that can be registered in a {@link View}
18416     * to enhance accessibility support via composition rather via inheritance.
18417     * It is specifically targeted to widget developers that extend basic View
18418     * classes i.e. classes in package android.view, that would like their
18419     * applications to be backwards compatible.
18420     * </p>
18421     * <div class="special reference">
18422     * <h3>Developer Guides</h3>
18423     * <p>For more information about making applications accessible, read the
18424     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18425     * developer guide.</p>
18426     * </div>
18427     * <p>
18428     * A scenario in which a developer would like to use an accessibility delegate
18429     * is overriding a method introduced in a later API version then the minimal API
18430     * version supported by the application. For example, the method
18431     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18432     * in API version 4 when the accessibility APIs were first introduced. If a
18433     * developer would like his application to run on API version 4 devices (assuming
18434     * all other APIs used by the application are version 4 or lower) and take advantage
18435     * of this method, instead of overriding the method which would break the application's
18436     * backwards compatibility, he can override the corresponding method in this
18437     * delegate and register the delegate in the target View if the API version of
18438     * the system is high enough i.e. the API version is same or higher to the API
18439     * version that introduced
18440     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18441     * </p>
18442     * <p>
18443     * Here is an example implementation:
18444     * </p>
18445     * <code><pre><p>
18446     * if (Build.VERSION.SDK_INT >= 14) {
18447     *     // If the API version is equal of higher than the version in
18448     *     // which onInitializeAccessibilityNodeInfo was introduced we
18449     *     // register a delegate with a customized implementation.
18450     *     View view = findViewById(R.id.view_id);
18451     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18452     *         public void onInitializeAccessibilityNodeInfo(View host,
18453     *                 AccessibilityNodeInfo info) {
18454     *             // Let the default implementation populate the info.
18455     *             super.onInitializeAccessibilityNodeInfo(host, info);
18456     *             // Set some other information.
18457     *             info.setEnabled(host.isEnabled());
18458     *         }
18459     *     });
18460     * }
18461     * </code></pre></p>
18462     * <p>
18463     * This delegate contains methods that correspond to the accessibility methods
18464     * in View. If a delegate has been specified the implementation in View hands
18465     * off handling to the corresponding method in this delegate. The default
18466     * implementation the delegate methods behaves exactly as the corresponding
18467     * method in View for the case of no accessibility delegate been set. Hence,
18468     * to customize the behavior of a View method, clients can override only the
18469     * corresponding delegate method without altering the behavior of the rest
18470     * accessibility related methods of the host view.
18471     * </p>
18472     */
18473    public static class AccessibilityDelegate {
18474
18475        /**
18476         * Sends an accessibility event of the given type. If accessibility is not
18477         * enabled this method has no effect.
18478         * <p>
18479         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18480         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18481         * been set.
18482         * </p>
18483         *
18484         * @param host The View hosting the delegate.
18485         * @param eventType The type of the event to send.
18486         *
18487         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18488         */
18489        public void sendAccessibilityEvent(View host, int eventType) {
18490            host.sendAccessibilityEventInternal(eventType);
18491        }
18492
18493        /**
18494         * Performs the specified accessibility action on the view. For
18495         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18496         * <p>
18497         * The default implementation behaves as
18498         * {@link View#performAccessibilityAction(int, Bundle)
18499         *  View#performAccessibilityAction(int, Bundle)} for the case of
18500         *  no accessibility delegate been set.
18501         * </p>
18502         *
18503         * @param action The action to perform.
18504         * @return Whether the action was performed.
18505         *
18506         * @see View#performAccessibilityAction(int, Bundle)
18507         *      View#performAccessibilityAction(int, Bundle)
18508         */
18509        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18510            return host.performAccessibilityActionInternal(action, args);
18511        }
18512
18513        /**
18514         * Sends an accessibility event. This method behaves exactly as
18515         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18516         * empty {@link AccessibilityEvent} and does not perform a check whether
18517         * accessibility is enabled.
18518         * <p>
18519         * The default implementation behaves as
18520         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18521         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18522         * the case of no accessibility delegate been set.
18523         * </p>
18524         *
18525         * @param host The View hosting the delegate.
18526         * @param event The event to send.
18527         *
18528         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18529         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18530         */
18531        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18532            host.sendAccessibilityEventUncheckedInternal(event);
18533        }
18534
18535        /**
18536         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18537         * to its children for adding their text content to the event.
18538         * <p>
18539         * The default implementation behaves as
18540         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18541         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18542         * the case of no accessibility delegate been set.
18543         * </p>
18544         *
18545         * @param host The View hosting the delegate.
18546         * @param event The event.
18547         * @return True if the event population was completed.
18548         *
18549         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18550         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18551         */
18552        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18553            return host.dispatchPopulateAccessibilityEventInternal(event);
18554        }
18555
18556        /**
18557         * Gives a chance to the host View to populate the accessibility event with its
18558         * text content.
18559         * <p>
18560         * The default implementation behaves as
18561         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18562         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18563         * the case of no accessibility delegate been set.
18564         * </p>
18565         *
18566         * @param host The View hosting the delegate.
18567         * @param event The accessibility event which to populate.
18568         *
18569         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18570         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18571         */
18572        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18573            host.onPopulateAccessibilityEventInternal(event);
18574        }
18575
18576        /**
18577         * Initializes an {@link AccessibilityEvent} with information about the
18578         * the host View which is the event source.
18579         * <p>
18580         * The default implementation behaves as
18581         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18582         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18583         * the case of no accessibility delegate been set.
18584         * </p>
18585         *
18586         * @param host The View hosting the delegate.
18587         * @param event The event to initialize.
18588         *
18589         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18590         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18591         */
18592        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18593            host.onInitializeAccessibilityEventInternal(event);
18594        }
18595
18596        /**
18597         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18598         * <p>
18599         * The default implementation behaves as
18600         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18601         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18602         * the case of no accessibility delegate been set.
18603         * </p>
18604         *
18605         * @param host The View hosting the delegate.
18606         * @param info The instance to initialize.
18607         *
18608         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18609         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18610         */
18611        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18612            host.onInitializeAccessibilityNodeInfoInternal(info);
18613        }
18614
18615        /**
18616         * Called when a child of the host View has requested sending an
18617         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18618         * to augment the event.
18619         * <p>
18620         * The default implementation behaves as
18621         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18622         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18623         * the case of no accessibility delegate been set.
18624         * </p>
18625         *
18626         * @param host The View hosting the delegate.
18627         * @param child The child which requests sending the event.
18628         * @param event The event to be sent.
18629         * @return True if the event should be sent
18630         *
18631         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18632         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18633         */
18634        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18635                AccessibilityEvent event) {
18636            return host.onRequestSendAccessibilityEventInternal(child, event);
18637        }
18638
18639        /**
18640         * Gets the provider for managing a virtual view hierarchy rooted at this View
18641         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18642         * that explore the window content.
18643         * <p>
18644         * The default implementation behaves as
18645         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18646         * the case of no accessibility delegate been set.
18647         * </p>
18648         *
18649         * @return The provider.
18650         *
18651         * @see AccessibilityNodeProvider
18652         */
18653        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18654            return null;
18655        }
18656    }
18657
18658    private class MatchIdPredicate implements Predicate<View> {
18659        public int mId;
18660
18661        @Override
18662        public boolean apply(View view) {
18663            return (view.mID == mId);
18664        }
18665    }
18666
18667    private class MatchLabelForPredicate implements Predicate<View> {
18668        private int mLabeledId;
18669
18670        @Override
18671        public boolean apply(View view) {
18672            return (view.mLabelForId == mLabeledId);
18673        }
18674    }
18675
18676    /**
18677     * Dump all private flags in readable format, useful for documentation and
18678     * sanity checking.
18679     */
18680    private static void dumpFlags() {
18681        final HashMap<String, String> found = Maps.newHashMap();
18682        try {
18683            for (Field field : View.class.getDeclaredFields()) {
18684                final int modifiers = field.getModifiers();
18685                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18686                    if (field.getType().equals(int.class)) {
18687                        final int value = field.getInt(null);
18688                        dumpFlag(found, field.getName(), value);
18689                    } else if (field.getType().equals(int[].class)) {
18690                        final int[] values = (int[]) field.get(null);
18691                        for (int i = 0; i < values.length; i++) {
18692                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18693                        }
18694                    }
18695                }
18696            }
18697        } catch (IllegalAccessException e) {
18698            throw new RuntimeException(e);
18699        }
18700
18701        final ArrayList<String> keys = Lists.newArrayList();
18702        keys.addAll(found.keySet());
18703        Collections.sort(keys);
18704        for (String key : keys) {
18705            Log.d(VIEW_LOG_TAG, found.get(key));
18706        }
18707    }
18708
18709    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18710        // Sort flags by prefix, then by bits, always keeping unique keys
18711        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18712        final int prefix = name.indexOf('_');
18713        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18714        final String output = bits + " " + name;
18715        found.put(key, output);
18716    }
18717}
18718